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

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

2 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 "";} 
1

It's possible to incorporate a variable within a regex expression by just putting $ in front of the variable ... no need to do ${}

so I suppose in your case

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

the regular expression will then be equal to by-kevin

I've had it work like this for a more complex regex rule

where I wanted orgin to match a list of possible domain names

set $domainWhitelist "yahoo\.com|google\.com|foo\.com"; if ($http_origin ~* "https?://([\w-]*\.)*($domainWhitelist)(:\d+)?") { ... } 
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like