I've spent some time trying to find the answer before writing this question:
I have several location
blocks in my nginx config file that look like this:
location ~ ^/(doc|img|bla|foo)/metadata/$ { ... }
location ~ ^/(doc|img|bla|foo)/deleted/$ { ... }
location ~ ^/(doc|img|bla|foo)/something/$ { ... }
So I thought it would be a good idea to refactor the repeated regular expression into a variable that I set in the server
section (also because I know I'll have to add to it in the future), like so:
server {
set $my_regex doc|img|blah|foo;
# I also tried this one:
set $my_regex "doc|img|blah|foo";
....
}
Which I would then reuse inside the location blocks:
# this doesn't have any effect
location ~ ^/($my_regex)/metadata/$ { ... }
# this one neither
location ~ ^/(\$my_regex)/deleted/$ { ... }
# and this one neither
location ~ ^/(${my_regex})/something/$ { ... }
Any idea? Thanks!
Best Answer
There is no way to use variables in
location
matching.If you want it, you probably doing something wrong. In this case you could try nesting locations.