Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert to lowercase in a mod_rewrite rule

I would like URLs like server.com/foo to be case-insensitive. But server.com/foo actually gets mod_rewrite'd to server.com/somedir/foo

(Assume that all the files in "somedir" are lower case.)

So the question is, how to accomplish a mod_rewrite like the following:

RewriteRule  ^([^/]+)/?$  somedir/convert_to_lowercase($1)

PS: Here's a handy mod_rewrite cheat sheet -- http://dreev.es/modrewrite -- though it fails to answer this particular question.

PPS: Thanks to Bee and Ignacio for all the help with this. Also, here's a related question: RewriteMap activation

like image 652
dreeves Avatar asked May 27 '10 18:05

dreeves


People also ask

How do I redirect urls to lowercase urls?

htaccess you can use mod_rewrite with an Apache expression in a RewriteCond directive to make use of the tolower() function. (You no longer need access to the server config to create a rewrite map.) This redirects/corrects any URL containing uppercase letters to the same - all lowercase - URL.

What is $1 rewrite rule?

In your rewrite, the ^ signifies the start of the string, the (. *) says to match anything, and the $ signifies the end of the string. So, basically, it's saying grab everything from the start to the end of the string and assign that value to $1.

What is rewrite condition?

The RewriteCond directive defines a rule condition. One or more RewriteCond can precede a RewriteRule directive. The following rule is then only used if both the current state of the URI matches its pattern, and if these conditions are met.


3 Answers

First, put the following line in the <VirtualHost> section of your .conf file. (For me that lives at /etc/httpd/vhosts.d/00foo.conf.)

RewriteMap lc int:tolower 

You can replace lc with any name you want. Then restart apache, which you can do with sudo service httpd restart.

Finally, add this in your .htaccess file:

RewriteRule ^/(.*)$ /${lc:$1} 
like image 137
dreeves Avatar answered Oct 18 '22 01:10

dreeves


RewriteMap tolower int:tolower
RewriteRule  ^([^/]+)/?$  somedir/${tolower:$1}
like image 45
Ignacio Vazquez-Abrams Avatar answered Oct 18 '22 02:10

Ignacio Vazquez-Abrams


I would make it a 301 redirect, NOT a URL rewrite, for SEO purposes:

RewriteMap tolower int:tolower
RewriteRule  ^([^/]+)/?$  somedir/${tolower:$1} [R=301,L]
like image 3
TommyBahama Avatar answered Oct 18 '22 00:10

TommyBahama