Query String Parameter Redirect
Example snippet showing how to redirect from one URL to another, changing only a single parameter in the query string. It’s a subtle but a commonly used technique, especially in the SEO field, where URLs are changed frequently to optimize for structure, keywords, etc.
The setup
So here is the scenario. We have URLs with this structure:
/cgi-bin/weather/weather.cgi?forecast=zandh&pands=27514&Submit=GO
..and the goal is to redirect them all to URLs with this structure:
/cgi-bin/weather/weather.cgi?forecast=avnmos&pands=27514&Submit=GO
Notice the difference? We’re changing the zandh
parameter to avnmos
. Everything else in the URLs should remain the same.
The solution
Here is how to accomplish this redirect using Apache’s mod_rewrite
. You can place this code in your site’s root .htaccess or the server config file:
# parameter redirect
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} /cgi-bin/weather/weather.cgi [NC]
RewriteCond %{QUERY_STRING} (forecast=)(zandh)(&pands=)([0-9]+)(&Submit=GO) [NC]
RewriteRule .* /cgi-bin/weather/weather.cgi?%1avnmos%3%4%5 [R=301,L]
</IfModule>
The trick here is to match up each of the parenthetical arguments (e.g., (forecast=)
, (zandh)
, etc.) with their corresponding representations (e.g., %1
, %2
, etc.) in the RewriteRule
. Take some time to study the logic used in this snippet.
Of course, this is just an example to demonstrate the technique. As you will no doubt be using different parameters, you will need to modify the code accordingly. Then as always remember to test well.