NGINX Dynamic Port proxy_pass

Solution 1:

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.