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?


location /$someport/servername/hls/ {
    proxy_buffers 16 4k;
    proxy_buffer_size 2k;

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;

^ 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!

Related Questions

IIS Output Caching with ISAPI extension

1  Asked on December 5, 2021


magento store views under sub folders with nginx

1  Asked on December 5, 2021 by pixelpaul


IAM policy that can delete snapshot on AWS

2  Asked on December 5, 2021 by golyat


Port forwarding on Linux without iptables?

8  Asked on December 3, 2021 by troex


Nginx http_mp4_module seam installed but dont work

1  Asked on December 3, 2021 by tahola


Apache 2.4 with LDAP Authentication

1  Asked on December 3, 2021 by pwe


How to configure squid-cache for this Payload?

0  Asked on December 3, 2021 by peridural


Ubuntu 18.04 server failed grub install

1  Asked on December 3, 2021 by scojo5


Ask a Question

Get help from others!

© 2022 All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir