Question about rewrite in nginx.conf using a variable ?

Stephen D. Scotti, M.D. sscotti at sias.dev
Sun Dec 12 05:27:07 UTC 2021


I have a configuration for a Docker NGINX container that works OK with my 'static' configuration, but I’d like to maybe use a variable in the proxy rewrite to avoid have to duplicate a location block for the server. A sample Static setup with some of the extra stuff removed is shown below.  That actually 'works' when I explicitly specify /pacs-1/ and /pacs-2/.  pacs-1 and pacs-2 happen to also be the name for other servers in my Docker Setup, so http://pacs-1:8042 <http://pacs-1:8042/> resolves to the docker container since it is called from Docker.  Those servers are not accessible outside of the container, which is one reason why I proxy some requests made to it from outside of the container.  I’m curious if it is possible to rewrite that such that I can match one of several container name from the request URI, e.g. something like location ~ ^/(pacs-butterfly|pacs-1|pacs-2)(/.*)   I tried various options, including setting a variable and nothing seems to work yet.

I could just create a separate block for each server, but it would be nice to generalize it so it would always work as long as the request uri corresponds to an existing container.  Thanks.
.

    location  /pacs-1/  {

        if ($request_method = 'OPTIONS') {
        	return 204;
        }

        auth_request /auth;
        auth_request_set $auth_status $upstream_status;
        proxy_buffering off;
        rewrite /pacs-1/(.*) /$1 break;
        proxy_pass http://pacs-1:8042 <http://pacs-1:8042/>;
        proxy_redirect  http://pacs-1:8042/ <http://pacs-1:8042/> /;
        proxy_set_header HOST $host;

    }

    location  /pacs-2/  {

        if ($request_method = 'OPTIONS') {
        	return 204;
        }

        auth_request /auth;
        auth_request_set $auth_status $upstream_status;
        proxy_buffering off;
        rewrite /pacs-2/(.*) /$1 break;
        proxy_pass http://pacs-2:8042 <http://pacs-2:8042/>;
        proxy_redirect  http://pacs-2:8042/ <http://pacs-2:8042/> /;
        proxy_set_header HOST $host;

    }

Stephen D. Scotti
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailman.nginx.org/pipermail/nginx/attachments/20211211/ccabd28e/attachment.htm>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 3887 bytes
Desc: not available
URL: <http://mailman.nginx.org/pipermail/nginx/attachments/20211211/ccabd28e/attachment.bin>


More information about the nginx mailing list