Sunday, October 14, 2007

Using Apache's mod_rewrite for multiple URL character substitutions with only one client redirect

If you need to replace a number of characters, and don't know how many times they're going to show up in a URL, here's how to make sure they get replaced using Apaches mod_rewrite.

The key here isn't really to do the substitution, but to do it any number of times (undetermined) and only redirect the client once!

RewriteRule ^/(.*)A(.*)$ /$1a$2 [N,E=redir:yes]
RewriteRule ^/(.*)B(.*)$ /$1b$2 [N,E=redir:yes]
RewriteCond %{ENV:redir} ^yes$

The RewriteRule lines can be as many as you like. The important thing is that, in the third part of the rule, N instructs mod rewrite only to redirect internally (rewrite without notifying the user browser) and set the environment variable redir to yes.

Then the RewriteCond line sends the redirect to the user browser once your URL is completely rewritten.

Enjoy :)

, MIke