基于java配置nginx獲取真實(shí)IP代碼實(shí)例
1、java代碼
/** 獲取客戶端IP */ public static final String getClientIp(HttpServletRequest request) { String ip = request.getHeader('X-Forwarded-For'); if (StringUtils.isBlank(ip) || 'unknown'.equalsIgnoreCase(ip)|| '127.0.0.1'.equalsIgnoreCase(ip)) { ip = request.getHeader('Proxy-Client-IP'); } if (StringUtils.isBlank(ip) || 'unknown'.equalsIgnoreCase(ip)|| '127.0.0.1'.equalsIgnoreCase(ip)) { ip = request.getHeader('WL-Proxy-Client-IP'); } if (StringUtils.isBlank(ip) || 'unknown'.equalsIgnoreCase(ip)|| '127.0.0.1'.equalsIgnoreCase(ip)) { ip = request.getHeader('X-Real-IP'); } if (StringUtils.isBlank(ip) || 'unknown'.equalsIgnoreCase(ip)|| '127.0.0.1'.equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } if (StringUtils.isBlank(ip) ||'127.0.0.1'.equals(ip)|| ip.indexOf(':') > -1) { try {ip = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) {ip = null; } } // 對于通過多個(gè)代理的情況,第一個(gè)IP為客戶端真實(shí)IP,多個(gè)IP按照’,’分割 if (ip != null && ip.length() > 15) { if (ip.indexOf(',') > 0) {ip = ip.substring(0, ip.indexOf(',')); } } return ip; }
2、nginx需要進(jìn)行相應(yīng)修改,重點(diǎn) proxy_set_header
server { listen xxxx; server_name 127.0.0.1; # 靜態(tài)頁面目錄 root xxxxxxxxxx; # 默認(rèn)首頁 index login.html; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header REMOTE-HOST $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods ’GET,POST’; add_header Access-Control-Allow-Headers ’DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization’; #proxy_cookie_path /* /*; client_max_body_size 100m; location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header REMOTE-HOST $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Headers ’DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization’; add_header Access-Control-Allow-Methods GET,POST,OPTIONS; ...... } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. asp文件如何打開2. Spring依賴注入的三種方式實(shí)例詳解3. JSP出現(xiàn)中文亂碼問題解決方法詳解4. 怎樣打開XML文件?xml文件如何打開?5. ASP基礎(chǔ)入門第二篇(ASP基礎(chǔ)知識(shí))6. ASP.NET MVC限制同一個(gè)IP地址單位時(shí)間間隔內(nèi)的請求次數(shù)7. ASP和PHP文件操作速度的對比8. ASP.NET MVC實(shí)現(xiàn)登錄后跳轉(zhuǎn)到原界面9. jsp實(shí)現(xiàn)局部刷新頁面、異步加載頁面的方法10. jsp實(shí)現(xiàn)簡單用戶7天內(nèi)免登錄
