Proxy Protocol是一种在代理服务器和后端服务器之间传递客户端原始连接信息的协议。以下是Nginx中配置使用Proxy Protocol的详细方法:
当Nginx作为后端服务器接收来自负载均衡器或代理服务器的Proxy Protocol信息时:
server {
listen 80 proxy_protocol;
listen 443 ssl proxy_protocol;
# 设置从proxy protocol中获取真实客户端IP
set_real_ip_from 192.168.1.0/24; # 代理服务器的IP段
set_real_ip_from 10.0.0.0/8;
real_ip_header proxy_protocol;
# 其他配置...
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
}
当Nginx作为代理服务器向后端服务器发送Proxy Protocol信息时:
location / {
proxy_pass http://backend_server;
# 启用proxy protocol v1
proxy_protocol on;
# 或者使用v2版本(需要Nginx 1.13.11+)
# proxy_protocol on v2;
}
http {
# 作为后端服务器接收PP
server {
listen 80 proxy_protocol;
server_name backend.example.com;
set_real_ip_from 192.168.1.0/24;
set_real_ip_from 10.0.0.0/8;
real_ip_header proxy_protocol;
access_log /var/log/nginx/access.log proxy;
location / {
root /var/www/html;
}
}
# 作为代理服务器发送PP
server {
listen 80;
server_name frontend.example.com;
location / {
proxy_pass http://backend.example.com;
proxy_protocol on; # 发送proxy protocol v1
# 其他代理设置
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
}
版本兼容性:
日志格式:如果需要记录原始客户端IP,需要在日志格式中使用$proxy_protocol_addr
变量:
log_format proxy '$proxy_protocol_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
健康检查:如果使用健康检查,确保负载均衡器在不使用Proxy Protocol的情况下进行健康检查,或者后端服务器能处理两种连接。
安全性:只接受来自可信代理服务器的Proxy Protocol连接:
allow 192.168.1.0/24;
allow 10.0.0.0/8;
deny all;
配置完成后,可以通过以下方式验证:
检查Nginx配置语法:
nginx -t
重新加载Nginx配置:
nginx -s reload
检查日志中是否记录了正确的客户端IP地址。
通过以上配置,Nginx可以正确地处理Proxy Protocol协议,确保在多层代理架构中能够获取到真实的客户端连接信息。