Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use a variable inside a nginx "if" regular expression

Tags:

regex

nginx

I have a caching system I need to bypass if the user's name (in a cookie) is found in the $request_uri. I'm trying to do something like this, but can't get the variable to interpolate into the regex. Any suggestions pretty please?

I can set the $me variable just fine from the cookie; I just can't get it to interpolate into the regex.

set $chk == "need";  set $me "kevin";  if ($uri ~ $me) { set $chk ""; }  if ($chk == "need") { rewrite ^ /testing } 

I've always tried things like this:

if ($uri ~ "by-{$me}") { set $chk ""; } 

Thanks! -Kevin

like image 521
Kevin Avatar asked May 02 '11 16:05

Kevin


People also ask

Can we pass variable in regex?

Note: Regex can be created in two ways first one is regex literal and the second one is regex constructor method ( new RegExp() ). If we try to pass a variable to the regex literal pattern it won't work. The right way of doing it is by using a regular expression constructor new RegExp() .

What type of regex does NGINX use?

Nginx uses the PCRE library.

What is map in NGINX?

The map module is a core Nginx module, which means it doesn't need to be installed separately to be used. To create the necessary map and redirect configuration, open the default server block Nginx configuration file in nano or your favorite text editor.

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.


1 Answers

It's not exactly what I asked, but I think it'll work for my purposes. I'm still curious how to interpolate a variable inside a nginx PCRE regex if anyone else knows!

set $chk == "need";  set $me "kevin";  if ($uri ~ /by-([^-]+)/) { set $by $1; } if ($by = $me) {set $chk "";} 
like image 158
Kevin Avatar answered Sep 17 '22 18:09

Kevin