插件窝 干货文章 nginx中怎么配置使用proxy protocol协议

nginx中怎么配置使用proxy protocol协议

Protocol Proxy Nginx 服务器 442    来源:    2025-04-23

在Nginx中配置使用Proxy Protocol协议

Proxy Protocol是一种在代理服务器和后端服务器之间传递客户端原始连接信息的协议。以下是Nginx中配置使用Proxy Protocol的详细方法:

1. 接收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;
}

2. 发送Proxy Protocol(作为代理服务器)

当Nginx作为代理服务器向后端服务器发送Proxy Protocol信息时:

location / {
    proxy_pass http://backend_server;

    # 启用proxy protocol v1
    proxy_protocol on;

    # 或者使用v2版本(需要Nginx 1.13.11+)
    # proxy_protocol on v2;
}

3. 完整示例配置

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;
        }
    }
}

4. 注意事项

  1. 版本兼容性

    • Proxy Protocol v1:所有版本支持
    • Proxy Protocol v2:需要Nginx 1.13.11+
  2. 日志格式:如果需要记录原始客户端IP,需要在日志格式中使用$proxy_protocol_addr变量:

    log_format proxy '$proxy_protocol_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent"';
    
  3. 健康检查:如果使用健康检查,确保负载均衡器在不使用Proxy Protocol的情况下进行健康检查,或者后端服务器能处理两种连接。

  4. 安全性:只接受来自可信代理服务器的Proxy Protocol连接:

    allow 192.168.1.0/24;
    allow 10.0.0.0/8;
    deny all;
    

5. 验证配置

配置完成后,可以通过以下方式验证:

  1. 检查Nginx配置语法:

    nginx -t
    
  2. 重新加载Nginx配置:

    nginx -s reload
    
  3. 检查日志中是否记录了正确的客户端IP地址。

通过以上配置,Nginx可以正确地处理Proxy Protocol协议,确保在多层代理架构中能够获取到真实的客户端连接信息。