ngxin代理如何获取用户真实IP

1、修改nginx配置文件

在location模块下添加如下配置获取代理前的用户IP

proxy_set_header X-real-ip $remote_addr;

修改后配置参考如下:

location / { try_files $uri $uri/ /index.html; proxy_set_header X-real-ip $remote_addr; }

2、java端获取用户IP

public static String getIpAddress() { HttpServletRequest request = getRequest(); String ip = request.getHeader("X-Real-IP"); //取nginx反向代理前的用户真实IP if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Forwarded-For"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 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.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; }