Welcome to my blog!

Here I try to keep useful information about IT, mostly related to Web development and Linux stuff. Any comments or feedback that you might have will be much appreciated!

Thanks,
Tomi

Query string based redirection with mod_rewrite

Filed Under (Linux, mod_rewrite) by admin on 31-07-2009

Today I was playing (more) with mod_rewrite, and came to an interesting requirement: how to redirect a page that receives a specific parameter value to another URL (as in article.php?id=57 to article.php?id=686)?

Normally you would use mod_rewrite to make clean URLs or to hide parameters as part of the query string.  Now, the requirement that I had this time was to redirect a page that received an specific parameter (thru query string), to a different page.

All the mod_rewrite rules that I tried wouldn’t work, until I paired them with RewriteCond.  Here is the sample:

RewriteCond %{QUERY_STRING} '=id=138'

RewriteRule ^product\.php? product.php?id=33 [R=301,L]

What this will do:

  1. Check if the query string is ‘id=138′  (note that we’re still not checking the file name receiving the parameter, we’re just checking the query string value).
  2. Perform the actual redirection to product.php?id=33 if the requested page is product.php (with the previously matched condition of ‘id=138′).

I used this trick to redirect visitors from product # 138 to product # 33  (take a visitor from product.php?id=138 to product.php?id=33).

Leave a Reply

You must be logged in to post a comment.