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
CodePudding user response:
Use this with multi-line flag
:
^(.*)(\/(?!no-trailing-slash)([^.\/]) )$
Replace any match with:
$1$2/
The pattern matches anything that after last /
neither has .
nor start with specific pattern and add /
at the end of them.
check Demo
CodePudding user response:
I actually figured it out with the help of HFZ's regex example. I used this and it works perfect:
^((?!no-trailing-slash)([^.]*[^\/]))$
and replace any match with:
$1/