Location Regex and ProxyPass Regex for NGINX conf

Viewed 1019

Wondering if there is a way to configure my nginx.conf file to use a regex to match my proxy url's in the location block and then also use a regex for the proxypass url. My setup current works fine when I have a static path, but I'd like to expand that to use 2 or more sort of like follows. The original is:

location  /pacs-1/  {

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

and I'd like to do something like the following, which clearly does not work (i.e. (?:pacs-butterfly|pacs-1|pacs-2)). For the proxy pass I need to use whatever path matched from the location block for the proxy rewrite and the proxy pass / redirects. Not sure that there is a way to do that.

location  /(pacs-butterfly|pacs-1|pacs-2)/ {  #match any of those in ()

. . . not sure how to code what I show below.

        auth_request /auth;
        auth_request_set $auth_status $upstream_status;
        proxy_buffering off;
        rewrite /(?:pacs-butterfly|pacs-1|pacs-2)/(.*) /$1 break;
        proxy_pass http://(?:pacs-butterfly|pacs-1|pacs-2):8042;
        proxy_redirect  http://(?:pacs-butterfly|pacs-1|pacs-2):8042/ /;
1 Answers

Looks like you're missing the ~ for Regex matching. Parentheses can be added to capture variables in $n format, and $request_uri is also available:

location ~ ^/(pacs-butterfly|pacs-1|pacs-2)(/.*) {
  default_type text/plain;
  return 200 "
    $1
    $2
    $request_uri
    $args
  ";
}
$ curl "https://example.com/pacs-1/foo/bar?name=value&foo=bar"

    pacs-1
    /foo/bar
    /pacs-1/foo/bar?name=value&foo=bar
    name=value&foo=bar
Related