1

I'm trying to make a rewrite rule in Nginx to remove trialing question mark (?) from urls but i can't get it right. I've done that for trailing slashes like this:

#redirect all trailing slash URL's to the respective non trailing slash
rewrite ^/(.*)/$ /$1 permanent;

so I figured the same would work just replacing the slash with the question mark:

rewrite ^/(.*)?$ /$1 permanent;

but that didn't work, but it occurred to me that the question mark has some significance in the regex so i tried escaping it:

rewrite ^/(.*)\?$ /$1 permanent;

but that didn't work either, I tried also removing the first slash:

rewrite ^(.*)\?$ $1 permanent;

but that was also a bust, and yes i did restart the server in between tests.

Here's what I am trying to do:

  • www.mysite.com? should redirect to wwww.mysite.com
  • www.mysite.com/some/path? should redirect to wwww.mysite.com/some/path
  • www.mysite.com?some=vars should remain unchanged.
  • www.mysite.com/some/path?some=vars should remain unchanged.

so basically only removing the question mark if there is no query string. How can i accomplish that?

I've checked other answers but they seem to want to remove the query string entirely, I only want to remove in the case that there is only a question mark and no parameters.

Julien
  • 242
  • 1
  • 3
  • 13
  • I have answered your question over on SO, [here](https://stackoverflow.com/questions/54058106/nginx-remove-trailing-question-mark/54066446#54066446) – Richard Smith Jan 06 '19 at 22:26

2 Answers2

1

Richard Smith gave me the answer on SO, i'll leave the answer here also in case someone ends up on this one:

if ($request_uri ~ ^(.*)\?$) { return 301 $1; }
Julien
  • 242
  • 1
  • 3
  • 13
0

Try the following:

if ($is_args) {
    if ($args = "") {
        return 301 $uri;
    }
}

I haven't tested this, so I am not sure if this will work. It all depends on what value nginx sets to $is_args when there is only the question mark in the URL and not any arguments.

Tero Kilkanen
  • 36,796
  • 3
  • 41
  • 63