.htaccess query string redirect

Added on: 2011-04-01 00:00:00 by: Emanuel

In this article we are going to learn how to configure a query string based redirect. One-by-one redirect, mass-redirect - everything about query string based redirects will become clear.

A few weeks ago we changed the layout of the site so we had to make sure users don't get any 404 errors when they try to access the old pages. We had to make sure every page is comfortably redirected to the new version.

We had dynamic urls that needed to be changed to static ones.

Since we had "?" in our urls we figured we can not use the classic single page redirect:

RewriteRule ^ApplicationsDesc.asp?id=64$ Download-ProgramX [R=301, NC, L]

because "?" would just be interpreted as the "match optional" regex operator.

So we had to try something different. Luckily we found out a "special" server-variable named REQUEST_URI.

First we tried the simplest way we could think of:

RewriteCond %{REQUEST_URI} /ApplicationsDesc.asp
RewriteCond %{QUERY_STRING} id=64
RewriteRule (.*) /Download-ProgramX/ [R=301, NC, L]

however we ran into an ugly side effect: the original query is passed through making our new url


Definately not we expected. After a long series of tries we figured out the way to fix this problem: just add an empty "?" at the end of your RewriteRule:

RewriteCond %{REQUEST_URI} /ApplicationsDesc.asp
RewriteCond %{QUERY_STRING} id=64
RewriteRule (.*) /Download-ProgramX/? [R=301, NC, L]

and voila the desired effect is accomplished.
Well not quite. In this form the rewrite rule will match not only ApplicationsDesc.asp?id=64, but ApplicationsDesc.asp?id=641 too. In fact it will match anything that starts with ApplicationsDesc.asp?id=64. Actually a great feature if you want to redirect a massive portion of your site to one url. To restrict the matching to only ApplicationsDesc.asp?id=64 is trivial: just put an ending "^" to the query string that is being matched like this:

RewriteCond %{REQUEST_URI} /ApplicationsDesc.asp
RewriteCond %{QUERY_STRING} id=64$
RewriteRule (.*) /Download-ProgramX/? [R=301, NC, L]

DownloadsArea Newsletter

Subscribe now and get all the important articles delivered directly to you.

More articles