Monday, November 9, 2009

Apache: mod_rewrite redirect when part of querystring matches

Recently a friend asked how to do a redirect with apache’s mod_rewrite if a part of the url’s query string matches.

After allot of trail and error I came to a solution.

Original Url:
htpp://example.com/old/index.php?param1=first¶m2=sometext

In this url the param1=first is static so won’t change.
The second parameter is not static, so it must not match this.

Redirect it to:
http://example.com/new/

There was no requirement to pass the query string to the new location.

So how to go about it?, won’t spend much time explaining(as I will most likely explain it wrong).
This is how to get the job done:

RewriteEngine On

RewriteCond %{QUERY_STRING} ^(.*&)?param1=first(&.*)?$ [NC]
RewriteCond %{QUERY_STRING} ^(.*&)?param2=[^&]+(&.*)?$ [NC]
RewriteRule ^(index\.php)?$ http://example.com/new/? [R=301,L]

Hope this will save some people time

No comments:

Post a Comment