Home > other >  .htacces redirect from upper case to lower case, except the last part of the URL
.htacces redirect from upper case to lower case, except the last part of the URL

Time:09-12

I need to redirect all address in my website from upper case to lower case, except the last part of the URL.

For example, I want to change

www.domain.com/a/B/C/XpTo

To

www.domain.com/a/b/c/XpTo

Only the last part (XpTo) remained unchanged.

However, I can also have:

www.domain.com/A/XpTo

And I need:

www.domain.com/a/XpTo

That is, even with a small path, only the last part must remain unchanged. How can I achieve that with .htaccess, without using RewriteMap in the Apache config file?

This is what I have tried:

RewriteEngine On

RewriteCond expr "tolower(%{REQUEST_URI}) =~ /(.*)/"
RewriteRule [A-Z] %1 [R=302,L]

CodePudding user response:

Your shown code will convert all of REQUEST_URI to lower case.

You can use a regex in RewriteRule pattern to match last part component separately from rest of URI and capture in a group. That can be used to put original value back on RewriteRule target.

Similarly leave last part component out of capture group in RewriteCond as well to get URI part before last component captured in %1.

You may use this code:

RewriteCond expr "tolower(%{REQUEST_URI}) =~ m#(. /)[^/] /?$#"
RewriteRule ^[^A-Z]*[A-Z].*/([^/] /?)$ %1$1 [R=302,L,NE]
  • Related