How to use a variable in a regular expression in nginx?
7,756
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.
Related videos on Youtube
Author by
jfix
Updated on September 18, 2022Comments
-
jfix over 1 year
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!
-
Admin about 6 yearsGreetings! Just interesting: did You try to combine two expressions in one?
location ~ ^/(doc|img|bla|foo)/(metadata|deleted|something)/$ { ... }
-
Admin about 6 years@SergeySerov No, I'm not going that far. I'm just trying to refactor the regular expression that has been used three times by assigning it to a variable that I then would like to use in the
location
directive. -
Admin about 6 years@SergeySerov Actually I now have combined them into one, and use a
rewrite
. But that doesn't solve the initial problem. :-)
-
-
jfix about 6 yearsI don't think I'm looking for named captures. From what I understand, named captures allow to reference a matched part of a regex by name rather than by a numeric index in later processing. Here however I'm looking for the possibility to reuse an existing variable inside a regex. Maybe that's just not possible?
-
jfix about 6 years@AlexeyTan I've reduced the use of the regex to only two occurrences which will make the pain of maintaining somewhat more bearable. But I guess I have to find another solution, maybe scripting?