Matmi

Geek Speak: Renaming URLs in Apache

Recently, I came across a problem when I had to migrate web content from a Windows IIS host to a Linux Apache host and some of the content had upper-case characters in the filenames.  On a Windows IIs platform ‘index.htm’ is the same as ‘Index.htm’, but Linux is case-sensitive, and so on a Linux Apache host, this is not the case.

The solution I used was to rename the content with all lower case directory and file names and write an .htaccess RewriteRule.  Our host had disabled RewriteMap for security reasons, so I had to use the less efficient pure RewriteRule variant. Credit and thanks to JDMorgan (Jim) for providing this example on a forum.

Using RewriteMap
Options +FollowSymlinks
RewriteEngine on
RewriteBase /
RewriteMap insensitive tolower:
RewriteRule ^[\/]*(.*)$ /${insensitive:$1} [R,L]

Without using RewriteMap
Options +FollowSymlinks
RewriteEngine on
RewriteBase /
# skip next 27 rules if no uppercase in URL
RewriteRule ![A-Z] – [S=27]
# else replace uppercase characters
RewriteRule ^([^A]*)A(.*)$ /$1a$2
RewriteRule ^([^B]*)B(.*)$ /$1b$2
RewriteRule ^([^C]*)C(.*)$ /$1c$2
RewriteRule ^([^D]*)D(.*)$ /$1d$2
RewriteRule ^([^E]*)E(.*)$ /$1e$2
RewriteRule ^([^F]*)F(.*)$ /$1f$2
RewriteRule ^([^G]*)G(.*)$ /$1g$2
RewriteRule ^([^H]*)H(.*)$ /$1h$2
RewriteRule ^([^I]*)I(.*)$ /$1i$2
RewriteRule ^([^J]*)J(.*)$ /$1j$2
RewriteRule ^([^K]*)K(.*)$ /$1k$2
RewriteRule ^([^L]*)L(.*)$ /$1l$2
RewriteRule ^([^M]*)M(.*)$ /$1m$2
RewriteRule ^([^N]*)N(.*)$ /$1n$2
RewriteRule ^([^O]*)O(.*)$ /$1o$2
RewriteRule ^([^P]*)P(.*)$ /$1p$2
RewriteRule ^([^Q]*)Q(.*)$ /$1q$2
RewriteRule ^([^R]*)R(.*)$ /$1r$2
RewriteRule ^([^S]*)S(.*)$ /$1s$2
RewriteRule ^([^T]*)T(.*)$ /$1t$2
RewriteRule ^([^U]*)U(.*)$ /$1u$2
RewriteRule ^([^V]*)V(.*)$ /$1v$2
RewriteRule ^([^W]*)W(.*)$ /$1w$2
RewriteRule ^([^X]*)X(.*)$ /$1x$2
RewriteRule ^([^Y]*)Y(.*)$ /$1y$2
RewriteRule ^([^Z]*)Z(.*)$ /$1z$2
# set flag to indicate character replacement, then restart mod_rewrite
# processing to catch multiple uppercase of same characters
RewriteRule .* – [E=changed:yes,N]
#
# (resume at rule below if all uppercase characters have been replaced
# or if there were no uppercase characters in the original URL)
#
# if any characters were replaced, execute rule
RewriteCond %{ENV:changed} ^yes$
RewriteRule (.*) /$1 [NC]



 Subscribe in a reader

Comments are closed.