34

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 2

30

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 "";}
Sign up to request clarification or add additional context in comments.

1 Comment

You have a syntax error on the first line, I think. The double equals operator shouldn't be there. I thought that was my problem for a second, but putting them into a config file won't pass any pre-launch checks.
-2

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 Comments

doesn't work for me. Logs show variable name instead: 2018/07/14 19:03:59 [notice] 6#0: *1 "https?://([\w-]*\.)*($domainWhitelist)(:\d+)?" does not match ...
There is an open issue on Github since 2013 saying this does not exist in nginx. I am curious if/how you got this to work. github.com/openresty/replace-filter-nginx-module/issues/5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.