Nginx+Tomcat+Springmvc獲取用戶訪問ip
1.Nginx反向代理
修改Nginx配置文件
location / { ***********之前代碼*******; proxy_set_header host $host; proxy_set_header X-forwarded-for $proxy_add_x_forwarded_for;//設置代理服務器ip頭,代碼獲取時的參數 proxy_set_header X-Real-IP $remote_addr; //允許將發送到被代理服務器的請求頭重新定義或者增加一些字段,顯示真實的客戶端的IP }
2.Springmvc代碼中添加方法
//Springmvc方法中添加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(); } Utils.log.info("【ip:" + ip + "】");//自己代碼里的日志打印