Nginx location block, redirect when not matching an expression

nginx

We're transitioning from a set of locations of the form: example.com/app1 where we will do a redirect to /app2.

However, we want to keep some URIs for app1 active, e.g., example.com/app1/111 and example.com/app1/222 should NOT redirect.

How should this be done? The location block doesn't accept a prefix like "!~", which would make it easy, i.e.,

location !~ /app1/(111|222) {
  rewrite /app1 /app2;
}

does not work in terms of the location pattern matching.

I've tried this (as well as putting parens around everything after /app1/), but it doesn't work either:

location ~ /app1/!(111|222) {
  rewrite /app1 /app2;
}

Suggestions?

Best Answer

cmiiw could you try (pls make sure the order is correct, and you may try to change the regex)

location ~ ^/app1/111$ {
  break;
}

location ~ ^/app1/222$ {
  break; 
}

location ~ ^/app1$ {
  rewrite /app1 /app2;
}
Related Topic