Marcin
Marcin

Reputation: 21

HTACCESS - upper case to lower case with exception

All URL paths must be in lower case When URL path has uppercase, redirect with 301 answer code to URL path only with lower case

I need to rule out the case where the uppercase letters in the url must stay for example

RewriteEngine On   
RewriteCond %{REQUEST_URI} [A-Z]   
RewriteRule . ${lc:%{REQUEST_URI}} [R=301,L]

This code in htaccess propably change upper case in url to lower case but i have no idea how to create exception for url like: https://example.com/testcase/1937Kdx88Ui9Ac where i need lower and upper case.

Upvotes: 2

Views: 295

Answers (1)

MrWhite
MrWhite

Reputation: 45914

RewriteCond %{REQUEST_URI} [A-Z]   
RewriteRule . ${lc:%{REQUEST_URI}} [R=301,L]

You don't need the separate condition here. The check for uppercase letters should be performed in the RewriteRule directive itself. For example, the above can be "simplified" to:

RewriteRule [A-Z] ${lc:%{REQUEST_URI}} [R=301,L]

You can then add "exceptions" (conditions) to exclude certain URLs from being converted. For example:

RewriteCond %{REQUEST_URI} !=/testcase/1937Kdx88Ui9Ac
RewriteRule [A-Z] ${lc:%{REQUEST_URI}} [R=301,L]

Multiple exceptions:

RewriteCond %{REQUEST_URI} !=/testcase/1937Kdx88Ui9Ac
RewriteCond %{REQUEST_URI} !=/testcase/FOO
RewriteCond %{REQUEST_URI} !=/testcase/BAR    
RewriteRule [A-Z] ${lc:%{REQUEST_URI}} [R=301,L]

The ! prefix on the CondPattern (2nd argument to the RewriteCond directive) negates the expression, so it is successful when the expression does not match.

The = operator makes it a lexicographical (exact match) string comparison instead of the normal regex.

Note that you will need to clear your browser cache, since any erroneous 301 (permanent) redirects will have been cached by the browser. Test first with a 302 (temporary) redirect to avoid potential caching issues.

NB: The use of the lc rewrite map requires that this has already been configured in the server config.

Upvotes: 3

Related Questions