I’m trying to add redirects in nginx config file where if a user lands on any URL except a specific one, it will add a trailing slash after it. Also, it shouldn’t add a trailing slash if there’s a .
in it.
Example:
- www.site.com/foo => www.site.com/foo/
- www.site.com/foo/baz => www.site.com/foo/baz/
- www.site.com/foo.xml => www.site.com/foo.xml (no trailing slash since there’s a
.
in the url) - www.site.com/no-trailing-slash => www.site.com/no-trailing-slash (no trailing slash specifically for this URL)
I did see this already which covers most of what I need:
#add trailing slash to all URLs except if it contains a .
rewrite ^([^.])*[^/]$ $1/ permanent;
I also figured out how to not add a trailing slash to a specific URL by doing something like this:
rewrite ^(?!no-trailing-slash).*[^/]$ $1/ permanent;
But I can’t figure out how to combine them so that:
- All redirects will add a trailing
/
- Unless they have a
.
in the URL - and doesn’t start with `/no-trailing-slash URL
2
Answers
I actually figured it out with the help of HFZ's regex example. I used this and it works perfect:
and replace any match with:
Use this with
multi-line flag
:Replace any match with:
The pattern matches anything that after last
/
neither has.
nor start with specific pattern and add/
at the end of them.check Demo