Nginx – How to remove the trailing slashes from a URL with nginx

nginxnode.jsredirect

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?

Best Answer

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 /.