TrumanWong

Nginx多出口IP解决代理端口数量限制

TrumanWong
3/9/2023

Nginx作为中继服务器的时候身份是属于client,那么ip就会被固定,serverip:port也是固定,那么连接数就受限于Nginx服务器本身的port数量:65535(实际上达不到,会有保留端口)。

因此,可以为Nginx服务器一个网卡配置多个IP,通过增加client端的ip数量来突破限制。Nginxproxy_bind虽然只能设置单一IP,没办法直接配置数组,但是可以设置变量(也支持透明传输),因此我们可以在不同的请求中对这个变量赋不同的IP,这样就能达到多出口的目的了。split_clients就可以帮我们完成上述功能。

配置文件如下:

http {
    ...
     upstream backend {
         server your_proxy_domain;
    }
    server {
        listen 80 default_server;
        server_name _;
        location / {
            proxy_pass http://backend;
            proxy_bind $split_ip;
            proxy_set_header X-Forwarded-For $remote_addr;
        }
    }
    # 只要请求过来,就会根据“uri+客户端端口”计算hash值,选出一个$split_ip,并赋给proxy_bind指令,就此完成了多出口IP的配置
    split_clients "$request_uri$remote_port" $split_ip {
        33%    192.168.16.128;
        33%    192.168.16.129;
        *      192.168.16.130;
    }
}

至此,Nginx改造完成,通过增加多个网卡或者IP则单台Nginx对外发起的Connect成倍增加,突破65535限制。