简体   繁体   中英

Nginx location statement behaves differently in regex and normal matching

I'm seeing different behaviour in these two cases:

location ~ /(?<version>v[12]) {
    proxy_pass https://localhost/api/$version;
}

location /v2 {
    proxy_pass https://localhost/api/v2;
}

If I request /v2/login , I see a request to /v2 in the regex configuration, whereas the direct match correctly retains the entire request url.

I tried adding a second capture group, /(?<version>v[12])/(?<path>.*) , and then it works, mostly. However, it seems to mess with PUT/POST.

Is there some explanation I'm missing? I read the documentation , but as far as I can tell there isn't supposed to be any difference between the use of regex or not using it.

Unfortunately, the official documentation lacks many importants notes. If you notice something unusual about Nginx that the documentation cannot explain, then I suggest checking with the wiki . In you case the interesting part is:

A special case is using variables in the proxy_pass statement: The requested URL is not used and you are fully responsible to construct the target URL yourself.

So, as soon as you introduced $version in your proxy_pass directive, Nginx started dismissing the original request URI, only sending what was in proxy_pass URI part.

That is why if you only need to cover two cases ( v1 and v2 ), I strongly recommend not to mess with regular expressions and instead just define two common prefix locations, like you did in your second example. Nginx configuration is not programming code and repeating parts of the configuration is quite alright.

However, if for some reason you really must use regular expression locations, you will have to either rewrite your URI:

location ~ /(?<version>v[12]) {
    rewrite ^/(.*)$ /api/$1 break;
    proxy_pass https://localhost;
}

Or construct the complete URI yourself:

location ~ /(?<version>v[12])(?<rest>.*)$ {
    proxy_pass https://localhost/api/$version$rest$is_args$args;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM