variable capture in Nginx location matching

Solution 1:

Old thread but I had the same problem...

I think the error isn't related to the PCRE version installed

NGINX doesn't parse your regex if your location tag doesn't start with ~ You need to use something like this

location ~ ^/a/b/(?<myvar>[a-zA-Z]+) {
   # use variable $myvar here
   if ($myvar = "sth") { ... }
}

Solution 2:

As Stefano Fratini correctly pointed out in his answer, your location declaration has an error: for regular expressions you should use ~ alone, not ^~.


Named captures are a feature of PCRE and they have different syntax available in different versions. For the syntax you use ?<var> you must have PCRE 7.0 at least.

Please see the extensive information in official Nginx documentation

Solution 3:

^~ is not regex match, it stands longest matching prefix. you should use ~ or ~* (case insenstive) instead

Solution 4:

Untested, but the correct way to capture a block into a named variable using PCRE is (?P). So your example misses the P.