RewriteRule redirect without the query stringPosted Feb. 22, 2013 in Apache
When redirecting all requests from one domain name to another one when the URL structure has changed, you'll ideally want to craft redirects from the old scheme to the new one. Sometimes this is too complex or messy, and it's easiest to just redirect everything to the new domain's homepage. If they have query strings at the end of the URL then Apache's RedirectMatch and RewriteRule with automatically include the query string in the redirect location. This post shows how to solve this.
We wanted all requests from old.example.com to go to new.example.com. This can be achieved easily like this in Apache:
<virtualhost *:80> ServerName old.example.com RedirectMatch permanent (.*) http://new.example.com/ </virtualhost>
or like this with a rewrite rule:
<virtualhost *:80> ServerName old.example.com RewriteEngine On RewriteRule .* http://new.example.com/ [R=301] </virtualhost>
The only problem was that the old domain we were redirecting from had stuff like this (this is a nice example, there were some pretty nasty URLs on the old website):
Using either of the above examples, this will redirect to:
While this may not cause any issues with the new domain/website, it's not really ideal. We don't want the ?idWebPage=50549 bit at the end.
The solution is rediculously easy. Simply add the ? after the rewrite rule target like so:
<virtualhost *:80> ServerName old.example.com RewriteEngine On RewriteRule .* http://new.example.com/? [R=301] </virtualhost>
http://old.example.com/afa.asp?idWebPage=50549 will now do a permanent redirect to http://new.example.com/ but it won't put ?idWebPage=50549 at the end, nor will it put ? at the end.