7

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?

Cory Fail
  • 173
  • 1
  • 5
  • 2
    Although not the best option. I’m going to do something like this: https://serverfault.com/questions/411832/dynamic-proxy-with-nginx-based-on-url-param – Cory Fail Jun 02 '18 at 19:08

2 Answers2

2

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.

uav
  • 494
  • 3
  • 16
0

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.

madacoda
  • 185
  • 7