2

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

This one will add a trailing slash to any URI except the /no-trailing-slash rewriting /foo/ to /foo// etc. Use ^(.*)(/(?!no-trailing-slash)([^.])*[^/.])$ to prevent it from adding a trailing slash to the URI already having that slash.
You are right, thanks.
1

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/

1 Comment

Hi @Alfonse, how can you do it with multiple URLs that should not have trailing slashes ^((?!no-trailing-slash)(?!no-trailing-slash-1)([^.]*[^\/]))$ or ^((?!no-trailing-slash|no-trailing-slash-1)([^.]*[^\/]))$ Not sure if any of these will work. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.