Through nginx reverse proxy, you cannot get the real IP. You get the nginx IP. To get the real IP, you need to configure the Nginx configuration file: nginx.conf
proxy_set_header X-Real-IP $remote_addr;
For example:
######################################################################## #要转发地域名: 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);
The above introduces how Tomcat obtains the real client IP instead of the server IP through nginx reverse proxy, including tomcat and nginx content. I hope it will be helpful to friends who are interested in PHP tutorials.