nginx做反向代理时,默认的配置后端获取到的ip都是来自于nginx,如何转发用户的真实ip到后端程序呢?如是是java后端,用request.getRemoteAddr();
获取到的是nginx的ip地址,而不是用户的真实ip.
修改nginx配置,如下:
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;
}
在原来配置的基础上加入后面的三条指令,就可以用request.getHeader("X-Forwarded-For");
获取到访客的ip了.
附:Java获取客户端ip的实现
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();
}
参考
- nginx反向代理获取用户真实ip
- nginx 如何配置来获取用户真实IP
- How to get Client IP Address using Java
- Getting IP address of client