2

Suppose the value of $request_uri is /a/b/c . The current value of $uri is /index.php . Is this possible to change my $uri to /b/c .

I have tried this, which doesn't seem to be working,

if ($request_uri ~* /a/(.*)/(.*)){
  set $uri /$1/$2;
}

But this gives error of duplicate "uri" variable. I also tried,

if ($request_uri ~* /a/(.*)/(.*)){
  rewrite ^ /$1/$2 break;
}

But $variables don't seem to store values.

Is there a way out? Thanks.

Satys
  • 183
  • 1
  • 2
  • 11

2 Answers2

3

Can you just use a temporary variable? Eg (not tried):

if ($request_uri ~* /a/(.*)/(.*)){
  set $tmp /$1/$2;
  rewrite ^ $tmp break;
}

or what about:

if ($request_uri ~* /a/(.*)/(.*)){
  rewrite ^ $request_uri;
  rewrite ^/[^/]*/(.*)/(.*) /$1/$2 break;
}
meuh
  • 1,563
  • 10
  • 11
  • yup I tried that, and I don't get anything in $1 and $2. can you think of any other alternative, please? – Satys Sep 02 '15 at 18:01
  • what about 2 rewites, updated answer. – meuh Sep 02 '15 at 18:09
  • Can you explain that a little, the second rewrite? – Satys Sep 02 '15 at 18:14
  • I just replaced `a` by `[^/]*` because you did `~*`, so you wanted to match uppercase and lowercase which I dont think you can do in rewrite. It just means any characters not including `/`. – meuh Sep 02 '15 at 18:17
  • I tried this one, it is also not working. And why did you not put flag for first rewrite? – Satys Sep 02 '15 at 18:26
  • If you mean the `break`, you cannot put it on the first rewrite as it will then stop doing any further commands. – meuh Sep 02 '15 at 18:30
  • Edited, Thanks man, it worked. I wasn't sure about flagless rewrite directive. Thank You Man. And sorry that I can't upvote you because I don't have enough reputations. Though I have put the same question on stackoverflow, if you can post the answer over there, I can upvote there. Thanks a ton. Can you ping me at satya8081@gmail.com for any further discussions. – Satys Sep 02 '15 at 18:36
  • waht is i have ti do it in reverse. $request_uri is "/a/b/c" but i need "/a/b/something _else" – Sheelpriy Dec 30 '16 at 09:20
1

As answered by @MTeck in https://stackoverflow.com/questions/9084969/nginx-request-uri-without-args

If you really want exactly $request_uri with the args stripped, you can do this.

local uri = string.gsub(ngx.var.request_uri, "?.*", "")

You will need to have lua available but that will do exactly what you're asking.