Gangaraju
Gangaraju

Reputation: 4562

nginx proxy_pass to dynamic url

I have multiple backend servers and I want to proxy all servers using a single nginx server instance. I don't want to change nginx.conf whenever I add a new backend server.

For example: Server 1 : 192.168.10.1:8080, Server2: 192.168.10.2:8080, etc Nginx is running on example.com. I want to access Server1 by using example.com?ip=192.168.10.1, example.com?ip=192.168.10.2 etc

I tried this configuration, but it is giving 500 error page.

location / {
   proxy_pass http://$arg_ip:8080;
   proxy_set_header Host      $host;
   proxy_set_header X-Real-IP $remote_addr;
}

Is there something I am missing? Is there any other way of achieving this?

Upvotes: 1

Views: 11534

Answers (1)

young
young

Reputation: 71

server {
    server_name dynamic_host;
    listern 8080;

    #resolver 8.8.8.8;
    #seems you don't need resolver because you use ip address

    location / {
        if ( $arg_address != "" ) {
            proxy_pass $arg_address;

            #proxy_pass $arg_address$uri
            #proxy_pass $arg_address$request_uri
        }

    }
}

the difference between the three proxy_pass

  1. $proxy_address
    example.com?address=http://192.168.10.2:8080/ goes to http://192.168.10.2:8080/

  2. $proxy_address$uri
    example.com/test/path?address=http://192.168.10.2:8080/ goes to
    http://192.168.10.2:8080/test/path

  3. $proxy_address$request_uri
    example.com/test/path?address=http://192.168.10.2:8080/&param=value goes to
    http://192.168.10.2:8080/test/path?address=http://192.168.10.2:8080/&param=value

you can change the param address to ip, in this case, don't forget to change $arg_address to $arg_ip.
reference:
http://nginx.org/en/docs/http/ngx_http_core_module.html#variables

Upvotes: 4

Related Questions