Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable capture in Nginx location matching

Tags:

regex

nginx

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 
like image 278
skyork Avatar asked Dec 04 '12 15:12

skyork


People also ask

How does Nginx match location?

To find a location match for an URI, NGINX first scans the locations that is defined using the prefix strings (without regular expression). Thereafter, the location with regular expressions are checked in order of their declaration in the configuration file.

What is regex in nginx?

Support for regular expressions is one of the powerful features of NGINX, but regexes can be complex and difficult to get right, especially if you don't work with them regularly. NGINX allows regexes in multiple parts of a configuration, for example locations, maps, rewrites, and server names.


1 Answers

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") { ... } } 
like image 192
Stefano Fratini Avatar answered Sep 25 '22 10:09

Stefano Fratini