skyork
skyork

Reputation: 7381

variable capture in Nginx location matching

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

Upvotes: 56

Views: 98614

Answers (4)

Alexander Azarov
Alexander Azarov

Reputation: 13221

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

Upvotes: 20

yabo
yabo

Reputation: 447

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

Upvotes: 9

Stefano Fratini
Stefano Fratini

Reputation: 3829

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") { ... }
}

Upvotes: 79

user1600649
user1600649

Reputation:

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

Upvotes: 3

Related Questions