0

Is there an Apache mod_rewrite script that will allow me to force lowercase URLs, except for a pagination segment?

For instance, I want the url https://domain.com/blog/Capitalized-Url/P10 to instead render as https://domain.com/blog/capitalized-url/P10.

1

I have got code used previously in .htaccess (not recently tested), but what you also have to be careful of is the filenames of other content, specifically images, etc. As both htaccess and Apache would do all URLs on the server.

As you've indicated in the question, the pagination urls don't work lowercase - the other one to watch out for is search results (I tend to use Low Search).

RewriteCond $1 [A-Z]
RewriteCond %{REQUEST_URI} !(\.pdf|\.jpg|\.jpeg|\.png)$ [NC]
RewriteCond %{REQUEST_URI} !/search/.* [NC]
RewriteCond !P[0-9]* [NC]
RewriteRule ^/?(.*)$ /${lowercase:$1} [R=301,L]

Breakdown...

RewriteCond $1 [A-Z]

Does the URL contain capital letters?

RewriteCond %{REQUEST_URI} !(\.pdf|\.jpg|\.jpeg|\.png)$ [NC]

Ignore if the requested URL ends in these extensions (extend with other extensions as applicable)

RewriteCond %{REQUEST_URI} !/search/.* [NC]

Ignore if the URL is search (change to match whatever you use if relevant)

RewriteCond !P[0-9]* [NC]

Ignore if it's a paginated URL

RewriteRule ^/?(.*)$ /${lowercase:$1} [R=301,L]

Now deliver the URL as lowercase.

EDIT

In the original answer, I didn't clarify the use of lowercase. This needs to be defined in the httpd.conf, like so:

RewriteMap lowercase int:tolower

The original solution provided meant that if there's a pagination identifier in the URL it ignores it completely, which means if you had /Blog/P10, it would allow it through. Alas I couldn't find a clean way of doing it in one regx, but this is the final solution I've used:

# Convert all URLs except if it has Pagination!
RewriteCond %{REQUEST_URI} ^[^A-Z]*[A-Z].*
RewriteCond %{REQUEST_URI} !(\.pdf|\.jpg|\.jpeg|\.png)$ [NC]
RewriteCond %{REQUEST_URI} !/search/.* [NC]
RewriteCond %{REQUEST_URI} !\/P[0-9]* [NC]
RewriteRule ^(.+?)$ https://%{SERVER_NAME}/${lowercase:$1} [R=301,L]

# If uppercase in initial URL, leaving Pagination element
# Will not match on lowercase intial or if Pagination element missing
RewriteCond %{REQUEST_URI} !(\.pdf|\.jpg|\.jpeg|\.png)$ [NC]
RewriteCond %{REQUEST_URI} !/holidays/search/.* [NC]
RewriteRule ^((.*?[A-Z]+.*)(\/P[0-9]+)) https://%{SERVER_NAME}/${lowercase:$2}$3 [R=301,L]
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.