Nginx/Haproxy作为反向代理或负载均衡时如何获取客户真实IP?

Nginx代理配置

增加如下配置:

1
2
3
4
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X_FORWARDED_PROTO https;
proxy_set_header Host $host;

Haproxy配置

1
option forwardfor

后端Nginx配置

1
2
3
set_real_ip_from 1.1.1.1; 前端Nginx代理或者负载均衡的IP(在后端Nginx日志中显示的)
real_ip_header X-Forwarded-For;
real_ip_recursive on;

后端Nginx访问控制

1
2
3
4
5
6
7
8
9
10
location ~ /test/api/ {
set $allow false;
if ($http_x_forwarded_for ~ "2.2.2.2") {
set $allow false;
}
if ($allow = false) { return 403;}
proxy_pass http://web;
}
}

参考

坚持原创分享,您的支持将鼓励我继续创作