通过nginx反向代理,就获取不到真实ip,是获取的nginx的ip,要得到真实的IP要进行配置Nginx的配置文件: nginx.conf
proxy_set_header X-Real-IP $remote_addr;
例如:
######################################################################## #要转发地域名: upstream t.csdn.com { server 192.168.1.188:8080 max_fails=0 weight=1; #8080为tomcat端口 } ################################################################## server { listen 80; server_name t.csdn.com; access_log /data/wwwlogs/access_tomcat.log combined; root /usr/local/tomcat/webapps; index index.html index.jsp; #反向代理配置,将所有请求为http://hostname的请求全部转发到upstream中定义的目标服务器中。 location / { #此处配置的域名必须与upstream的域名一致,才能转发。 proxy_pass http://t.csdn.com; proxy_set_header X-Real-IP $remote_addr; } #启用nginx status 监听页面 location /nginxstatus { stub_status on; access_log on; } }
private static String getRemoteAddrIp(HttpServletRequest request) { String ipFromNginx = getHeader(request, "X-Real-IP"); log.info("ipFromNginx:" + ipFromNginx); log.info("getRemoteAddr:" + request.getRemoteAddr()); return StringUtils.isEmpty(ipFromNginx) ? request.getRemoteAddr() : ipFromNginx; } private static String getHeader(HttpServletRequest request, String headName) { String value = request.getHeader(headName); return (StringUtils.isNotBlank(value) && !"unknown" .equalsIgnoreCase(value)) ? value : ""; }
String clientIp = getRemoteAddrIp(request); log.info("客户IP:" + clientIp);
以上就介绍了通过nginx反向代理,Tomcat获取真实的客户端IP而非服务器IP,包括了tomcat,nginx方面的内容,希望对PHP教程有兴趣的朋友有所帮助。