nginxnginx-location

NGINX Location matching wrong similar location


We are migrating off an old api onto a new api. We will eventually update the front end code but for now are doing it in nginx.

        #location /vapi {
        # old api
        location ~ ^/vapi/(?!(sites))/.+$ {
            add_header Access-Control-Allow-Origin $cors_header;
            access_log  logs/vapi.proxy.log lfupstream;
            error_log  logs/vapi.error.log error;
            rewrite ^/vapi/(.*)$ /$1 break;
            proxy_pass http://vapi;
        }
        # new api
        location ~ ^/vapi/sites/.+$ {
            add_header Access-Control-Allow-Origin $cors_header;
            access_log  logs/vapi.portal.proxy.log lfupstream;
            error_log  logs/vapi.portal.error.log error;
            rewrite ^(.*)$ /api/$1 break;
            proxy_pass https://portal;
        }

The old api is matching https://exa.valor.network/vapi/sites/SITE-NAME Have also tried:

location /vapi {
...
}
location /vapi/sites {
...
}

and

location /vapi {
...
}
location ~^/vapi/sites/.+$ {
...
}

Ref: Nginx location "not equal to" regex Ref: Nginx location priority


Solution

  • Beside the fact I was on a test nginx and not the dev nginx Richard Smith's comment was a solution that worked. I had misread how nginx selected regex location as the longest had the highest priority. I ended up going with a regex for the new api and left the old api as is with a Prefix match thus the new api location takes priority if matched otherwise the old api gets the match.

    Thanks to Richard Smith.

        # new api
        location ^~ /vapi/sites {
            rewrite ^/(.*)$ /api/$1 break;
            proxy_pass https://portal;
        }
        # old api
        location /vapi {
          rewrite ^/vapi/(.*)$ /$1 break;
          proxy_pass http://$vapi_service;
        }