nginx 使用负载平衡将请求转发到不同的 URL

nginx 使用负载平衡将请求转发到不同的 URL

我是 nginx 的新手,我使用它来转发请求,每个传入的请求都会转发到另一个服务器/url,下面是我的配置:

    http {
        include       mime.types;
        default_type  application/octet-stream;
        sendfile on;  
        keepalive_timeout  65;
        
        server {
            listen       8008 ssl;
            listen       localhost:8008 ssl;
            listen       xyz.exmaple.com:8008 ssl;
            server_name  xyz.exmaple.com;
            more_set_headers 'Server: ABC';
            
            ssl_protocols TLSv1.2;
            ssl_prefer_server_ciphers on;
            ssl_ciphers "EECDH+AESGCM,EDH+AESGCM";      
            ssl_certificate /logs/ssl/SSL.crt;      
            ssl_certificate_key /logs/ssl/key.key;

location /app/ {
        
            
            proxy_pass      https://proxy1.example.com:8888/abc/efg;            
            proxy_read_timeout 60s;

            # May not need or want to set Host. Should default to the above hostname.
            proxy_pass_header Server;
            proxy_set_header          Host            $host;
            proxy_set_header          X-Real-IP       $remote_addr;
            proxy_set_header          X-Forwarded-For $proxy_add_x_forwarded_for;
            add_header  X-Frame-Options "SAMEORIGIN" always;
            more_set_headers 'Server: ABC';
            
        }
        
        }

}  

上的每个请求https://xyz.exmaple.com:8008/app/正在转发至https://proxy1.example.com:8888/abc/efg

现在我有两个 URL:

1) https://proxy1.example.com:8888/abc/efg
2) https://proxy2.example.com:8888/abc/efg

我想要对这两个 URL 进行循环负载平衡,我该如何实现?

答案1

用于upstream解决此问题。例如:

http
{
    include mime.types;
    default_type application/octet-stream;
    sendfile on;
    keepalive_timeout 65;

    upstream backend
    {
        server proxy1.example.com:8888;
        server proxy2.example.com:8888;
    }

    server
    {
        listen 8008 ssl;
        listen localhost:8008 ssl;
        listen xyz.exmaple.com:8008 ssl;
        server_name xyz.exmaple.com;
        more_set_headers 'Server: ABC';

        ssl_protocols TLSv1.2;
        ssl_prefer_server_ciphers on;
        ssl_ciphers "EECDH+AESGCM,EDH+AESGCM";
        ssl_certificate /logs/ssl/SSL.crt;
        ssl_certificate_key /logs/ssl/key.key;

        location /app/
        {
            proxy_pass https://backend/abc/efg;
            proxy_read_timeout 60s;

            # May not need or want to set Host. Should default to the above hostname.
            proxy_pass_header Server;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            add_header X-Frame-Options "SAMEORIGIN" always;
            more_set_headers 'Server: ABC';
        }

    }

}

相关内容