When nginx is used as the reverse proxy, the ip obtained by the default configuration backend is from nginx. How to forward the user's real ip to the backend program? For example, in java backend, use request.getRemoteAddr(); obtain the nginx ip address, not the user's real ip address
Modify nginx configuration as follows:
upstream www.xxx.com { ip_hash; server serving-server1.com:80; server serving-server2.com:80; } server { listen www.xxx.com:80; server_name www.xxx.com; location / { proxy_pass http://www.xxx.cn; } proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }
After adding the following three instructions to the original configuration, you can use request.getHeader("X-Forwarded-For"); to get the ip address of the visitor
Appendix: the implementation of getting client ip by Java
private static final String[] IP_HEADER_CANDIDATES = { "X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED", "HTTP_X_CLUSTER_CLIENT_IP", "HTTP_CLIENT_IP", "HTTP_FORWARDED_FOR", "HTTP_FORWARDED", "HTTP_VIA", "REMOTE_ADDR" }; public static String getClientIpAddress(HttpServletRequest request) { for (String header : IP_HEADER_CANDIDATES) { String ip = request.getHeader(header); if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) { int index = ip.indexOf(","); if (index != -1) { return ip.substring(0, index); } return ip; } } return request.getRemoteAddr(); }