NGINX Dynamic Port proxy_pass

nginxproxypass

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?

Best Answer

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.

Related Topic