nginx代理tomcat不能獲取真實ip地址解決方法java
2016年05月27日 11:04:06nginx
閱讀數:2205tomcat
本文介紹了nginx服務器代理tomcat系統時,不能獲取真實ip地址的解決辦法,有須要的朋友參考下。服務器
nginx代理tomcat時,tomcat獲取的客戶端不是客戶端傳過來的ip。
緣由分析:
nginx做爲代理服務器先攔截客戶端發來的請求,它再以localhost的身份轉發給tomcat去處理。代理
解決辦法:
在nginx配置中的location節點中添加:
ip
複製代碼代碼示例:rem
proxy_set_header Host $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;get
java中這樣獲取遠程ip地址:
io
複製代碼代碼示例:配置
public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; }