Home > Back-end >  Nginx: How to add a trailing slash to URL except if it starts with certain name
Nginx: How to add a trailing slash to URL except if it starts with certain name

Time:10-16

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:

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:

  1. All redirects will add a trailing /
  2. Unless they have a . in the URL
  3. 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/
  • Related