2

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?

4
  • 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. Commented Apr 25, 2020 at 1: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. Commented Apr 25, 2020 at 1: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. Commented Apr 25, 2020 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? Commented Apr 25, 2020 at 11:19

4 Answers 4

1

It seems like the good variant will be the next config:

if ($request_uri ~* (.*?)(\/+)$) { return 301 $scheme://$host$1; } 
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 /.

2
  • this results in "too many redirects" for me @Gerard Commented Mar 8, 2021 at 16:14
  • Not from this rewrite, @AATHITHRAJENDRAN. Better open a new question with your full nginx configuration. Commented Mar 8, 2021 at 16:53
0

This one worker for me:

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

This solution has also been tested and works well.

It should have a better performance because there is no rewriting according to the best practice above.

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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.