生产上,配置NGINX的反向代理,为了统计IP访问记录,需要代理服务器知道来自用户的IP,这部分应该怎样实现。
第一步:NGINX的反向代理的配置

upstream MLSCHECK{
server 10.3.51.XX:9802 weight=3 max_fails=3 fail_timeout=10s;
server 10.3.XXX.XXX:9802 weight=3 max_fails=3 fail_timeout=10s;
server 10.3.51.126:9802 weight=3 max_fails=3 fail_timeout=10s;

}

server {
listen 80;
server_name mlscheck.runchina.org.cn;

location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header HTTP_X_FORWARDED_FOR $remote_addr;
proxy_redirect off;
client_max_body_size 50m;
client_body_buffer_size 256k;
proxy_connect_timeout 30;
proxy_send_timeout 30;
proxy_read_timeout 60;
proxy_buffer_size 256k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
proxy_temp_file_write_size 256k;
proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;
proxy_max_temp_file_size 128m;
proxy_pass http://MLSCHECK/;
}
}

关键配置项

-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;

第二步:后端的java代码的写法

public String getClientIP(HttpServletRequest request) {   
String 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.getRemoteAddr();
}
return ip;
}

这样就能获取来自客户端的真实的IP了