NGINX: redirect url to custom port with reverse proxy using if

Viewed 307

I'm trying to rewrite the URL. I want to be able to determine the port number from the url, and nginx proxy it to the localhost:'that port'.

https://app.localtest.com/dev/sender -> https://localhost:44638

Based on what is after '/dev/', the port will be determined.

eg. https://app.localtest.com/dev/receiver -> https://localhost:44639

server {
listen          80;
server_name     app.localtest.com;

location ~ ^/dev/(.*)$ {
        set $port_num 0; 
        if ($1 = 'sender'){
            set $port_num 44368;
            }
        proxy_pass https://localhost:$port_num/;
    }
}

But this throws error: nginx: [emerg] unknown "1" variable

1 Answers

You can create multiple location sections:

server {
    listen          80;
    server_name     app.localtest.com;

    location ~ ^/dev/sender {
        proxy_pass https://localhost:44638/;
    }
    location ~ ^/dev/receiver {
        proxy_pass https://localhost:44639/;
    }
}
Related