Updated November 02, 2017

We are often asked “How do I redirect a url based on the query string?”. You would expect the following to work and send your visitors to the page you expect:

Redirect /sample.php?id=1 http://example.com/sample/1

Too bad this won’t work. htaccess does not really allow you to specify a query string to determine the redirection.

Instead of redirecting we will have to use mod_rewrite to change the url. Set rewrite to enabled, if not already included in your .htaccess file. If mod_rewrite Apache module is not installed and enabled contact your server administrator to install/enable.

Start by checking for the page you plan to redirect. In this case we are looking for a match to “sample.php” in the REQUEST_URI. If found we will continue to check for a query string match for “id=1”. This will allow us to make a Rewrite based on the query.

Pretty Simple, but sure can be tricky. Try the testing tool to determine what matches and what is failing in your htaccess redirect/rewrite. http://htaccess.madewithlove.be/

RewriteEngine On
RewriteCond %{REQUEST_URI} /sample\.php$
RewriteCond %{QUERY_STRING} ^id=1$
RewriteRule .* http://example.com/sample/ [R=301,L]