I am writing a location block for a Nginx config, and it is for URIs with pattern like this: www.mysite.com/a/b/blah/c
or www.mysite.com/a/b/blah/c/n
.
Where a
and b
are fixed, blah
may vary, c
can be one of three fixed strings (optionA, optionB, optionC) only, and n
is a digit starting from 0, 1, 2, and so on. In addition, n
is valid only when c
is equal to optionB, so that in any other case Nginx should throw a 404
immediately if there is anything after c
.
I intend to write a location block as:
location ^~ /a/b/ {
...
}
The logic I want to implement inside this location: first capture c
from a given URI, and based on its value, do one of three possible rewrites. i.e.
if (c = optionA) {
rewrite ... ... break;
}
if (c = optionB) {
rewrite ... ... break;
}
if (c = optionC) {
rewrite ... ... break;
}
My questions are:
-
I have read that
if
statement should be generally avoided in location block in Nginx, but it seems like its use withrewrite
is an exception. Will the way I userewrite
here cause any problem? -
How do I capture
c
and implement the conditional rewrite logic here?
Best Answer
use regexp, something like: www.mysite.com/(.)/(.)/blah/c and $1, $2 for founded url's parts.