Netra
Netra

Reputation: 338

Lowercasing all urls except some using Nginix

For some time now I'm struggling to find an easy solution ( if there is one ) for lowercasing all the urls of my website but excluding some paths.

Long story short what I'm trying to achieve is to match any urls that have uppercases in their names in order to redirect them to the lowercase version but exclude exact paths like domain.com/audio/* , diomain.com/video/

I cant seem to find a way to do it and also cover all the possible cases. I tried doing something like this:

location ~ ^(?!\/(audio|video)\b).+[^a-z]
 {
   # do redirect
 }
}

The above condition covers a part of the cases for example:

but it also excludes paths that have audio or video as the first part of the path and also doesn't match path trees, ex:

Am I going into the wrong direction with this? I feel like I'm overcomplicating something that should be easier.

Upvotes: 1

Views: 32

Answers (1)

The fourth bird
The fourth bird

Reputation: 163217

About the pattern you tried

  • Using [^a-z] matches any char except a-z, which matches more than only A-Z and will also match /

  • Using .+[^a-z] will first match until the end of the string, and will then backtrack to match the first occurrence of any char except a-z which in this part will be the E in the last Elmo and then the match will stop as that is where the pattern ends.

    /elmo/Elmo/Elmo
    ^^^^^^^^^^^^ 
    
  • The pattern does not match audio-HELP because there is a word boundary between the o and the - which will make the assertion fail.


You might use a negative lookahead to assert what is directly to the right is not audio or video followed by an optional / and the end of the string.

Then match at least a single uppercase char A-Z and the rest of the line.

^(?!\/(?:audio|video)\/?$).+[A-Z].*

Regex demo

Upvotes: 1

Related Questions