Let's say I have a URL like this: www.example.com/a/b/sth
, and I write a location block in Nginx config:
location ^~ /a/b/(?<myvar>[a-zA-Z]+) {
# use variable $myvar here
if ($myvar = "sth") { ... }
}
I hope to be able to use variable $myvar
captured from the URL inside the block, however, Nginx keeps telling me this variable is not defined and won't start:
nginx: [emerg] unknown "myvar" variable
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") { ... }
}
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
^~ is not regex match, it stands longest matching prefix. you should use ~ or ~* (case insenstive) instead
Untested, but the correct way to capture a block into a named variable using PCRE is (?P). So your example misses the P.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.