基于java配置nginx獲取真實IP代碼實例
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; } } // 對于通過多個代理的情況,第一個IP為客戶端真實IP,多個IP按照’,’分割 if (ip != null && ip.length() > 15) { if (ip.indexOf(',') > 0) {ip = ip.substring(0, ip.indexOf(',')); } } return ip; }
2、nginx需要進行相應修改,重點 proxy_set_header
server { listen xxxx; server_name 127.0.0.1; # 靜態(tài)頁面目錄 root xxxxxxxxxx; # 默認首頁 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; ...... } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. 解決Android studio xml界面無法預覽問題2. 什么是python的自省3. Springboot Druid 自定義加密數(shù)據(jù)庫密碼的幾種方案4. Spring Boot和Thymeleaf整合結合JPA實現(xiàn)分頁效果(實例代碼)5. 詳解Android studio 動態(tài)fragment的用法6. Vuex localStorage的具體使用7. php模擬實現(xiàn)斗地主發(fā)牌8. IntelliJ IDEA安裝插件的方法步驟9. Vue封裝一個TodoList的案例與瀏覽器本地緩存的應用實現(xiàn)10. 使用Android studio查看Kotlin的字節(jié)碼教程

網公網安備