How to access nginx multiple servers from same location in nginx

27 Views Asked by At

Here I have multiple severs I want to access that server in same location path in proxy_pass what be the changes. using this code I always points to first server how to points to second server.

upstream my/api/call {
        server 192.168.12.38:3004;   
        server 192.168.12.38:3500;  
        
    }
    
    location ~ ^/my/api/call(/?)(.*) {
           proxy_pass http://192.168.12.38:3004/my/api/call$2?$args;
            proxy_buffer_size 128k;
            proxy_buffers 4 256k;
            proxy_busy_buffers_size 256k;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Host $host;
            proxy_`enter code here`set_header X-Forwarded-For 
            $proxy_add_x_forwarded_for;
        }
1

There are 1 best solutions below

0
Hamid Ostadvali On

You use upstream incorrectly. In your example you sent the traffic only to 192.168.12.38:3004.

proxy_pass http://192.168.12.38:3004/my/api/call$2?$args;

First, you need to give a name to the upstream and then set that name to proxy_pass. For example:

upstream my_api_call {
        server 192.168.12.38:3004;   
        server 192.168.12.38:3500;  
        
    }
    
    location ~ ^/my/api/call(/?)(.*) {
            proxy_pass http://my_api_call/my/api/call$2?$args;
            proxy_buffer_size 128k;
            proxy_buffers 4 256k;
            proxy_busy_buffers_size 256k;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Host $host;
            proxy_`enter code here`set_header X-Forwarded-For 
            $proxy_add_x_forwarded_for;
        }