Combin several proxy_pass location paths in nginx

Hi I have several locations for proxy_pass, e.g.:

location /v1 {
    proxy_pass http://localhost:8080/myapp/v1;
    # other stuff
}
location /v2 {
    proxy_pass http://localhost:8080/myapp/v2;
    # other stuff
}
location /beta {
    proxy_pass http://localhost:8080/myapp/beta;
    # other stuff
}
location / {
    root C:/MyApp/build/;
}

Is there a way to combine the top three location paths (v1, v2, beta) into one location config? As they are quite the same (same other stuff as well) except the end bits of the proxy_pass. Thank you.


Solution 1:

The "other stuff" can probably move into the outer block so that the three location blocks only need to contain a single proxy_pass statement.

But you can use a regular expression location to match any URI beginning with /v1, /v2, and /beta.

For example:

location ~ ^/(v1|v2|beta) {
    rewrite ^(.*)$ /myapp$1 break;
    proxy_pass http://localhost:8080;
    # other stuff
}

Note that the evaluation order of regular expression location blocks is significant. This will not affect you if the only other location block in your server block is location /. See this document for details.

Solution 2:

You can use:

location ~ ^/(?<dest>v1|v2|beta) {
    proxy_pass http://localhost:8000/myapp/$dest;
    # other stuff
}

This might cause some side-effects depending on your other configuration in the server block.