Nginx Remove Trailing Question Mark From URL

nginxrewrite

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.

Best Answer

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; }