0

I'm trying to remove trailing slashes from urls. I searched a lot and tried some solutions but they didn't work form me.

I tried this one

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

but it leaves one slash at the end (example.com/ or example.com/post/) but I need example.com and example.com/post

Also I tried this solution

if ($request_uri ~ (.*?\/)(\/+)$ ) 
{
  return 301 $scheme://$host$1;
}

and it's one of the best but it also leaves one slash at the end.

And also I was getting an error in the console after all tries like this:

GET http://example.com/post 404 (Not Found)

I'm new to nginx and doesn't know a lot, how can I achieve redirects from urls with trailing slashes?

Igor Oleniuk
  • 1
  • 1
  • 3
  • How many backslashes are being requested. Have you got urls like example.com/// or something silly like that. The rewrite you have used should work, but I guess Nginx assumes only one backslash. You might need to repeat it for // and /// etc. – Admiral Noisy Bottom Apr 25 '20 at 01:47
  • 1
    Why do you want to do that? In case of "example.com/", that slash isn't "trailing", it's the first character of every url. Remove it, your browserr will add it again. – Gerard H. Pille Apr 25 '20 at 01:56
  • @GerardH.Pille agree with that, but how can I remove slash in this case 'example.com/post/'? Because when I'm trying url like this 'example.com/post////' it leaves one slash at the end - 'example.com/post/', I want remove that slash too. – Igor Oleniuk Apr 25 '20 at 11:15
  • @AdmiralNoisyBottom, two and more slashes are being requested ( example.com//////), I'll try to repeat that rewrite, but how exactly should I do that just paste few of them or make some changes? – Igor Oleniuk Apr 25 '20 at 11:19

2 Answers2

0

No ifs (or buts) are needed, a rewrite will do:

rewrite /((?U).*)(/+)$ /$1 redirect;

Without the "ungreedy" - (?U) - $1 would pick up all but one /.

Gerard H. Pille
  • 2,569
  • 1
  • 13
  • 11
0

This one worker for me:

location ~ (.*)/$ {
  if ($query_string) {
    return 301 $scheme://$host$1?$query_string;
  }
  return 301 $scheme://$host$1;
}
Mechanic
  • 101
  • 2