TransWikia.com

NGINX Dynamic Port proxy_pass

Server Fault Asked by fyroc on November 8, 2020

I need a way to proxy_pass a dynamic port through the location’s URL. The proxy has the same IP but the port changes since the servers are created via docker on random port numbers. (Too many for me to add manually)

I need a way to proxy_pass these URLs and ports dynamically. I was thinking I could some how pass in the port number via URL variable?

Example:

location /$someport/servername/hls/ {
    proxy_buffers 16 4k;
    proxy_buffer_size 2k;
    proxy_pass http://216.189.210.65:$someport;
}

Is there a way I can do this?

2 Answers

Regex to the rescue (~). Make the capture group with parentheses and use the first one with $1. Use the second parentheses with $2 or better $myuri. I save $2 in $myuri and $args in $myargs to preserve/encode possible spaces!

location ~ ^/([0-9]+)(/servername/hls/.*)$ {
    set $myuri  $2;     # set preserves/encodes spaces!!
    set $myargs $args;  # set preserves/encodes spaces!!
    proxy_buffers 16 4k;
    proxy_buffer_size 2k;
    proxy_pass http://216.189.210.65:$1$myuri$is_args$myargs;
}

^ is the beginning of the $request_uri. + matches one or more (numbers). . is any character. * is none, one or more (characters). $ is the end of the location (before query string).

Because the nginx location cannot match the query string after the question mark, you have to add $is_args$args or better $is_args$myargs.

I remember doing something in the past and it worked right away. Untested.

Answered by uav on November 8, 2020

Not sure if Nginx will pull your shell variables.

If it is running on the same server, you can still do this by injecting the server block with the new port number (cat, grep, sed, etc) and then restarting or reloading nginx with the new file.

It is definitely doable via bash.

Answered by madacoda on November 8, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP