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 + "】");//自己代码里的日志打印
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/19441.html