How to discard the query string in a RewriteRule (Apache, mod_rewrite)

Removing the query string in a rewrite rule of Apache's module modrewrite is a bit tricky. Let's say you want to redirect the url http://www.example.com?query=test to http://www.example.com/noqueries in Apache with modrewrite enabled. Rewriting the URL is no problem but Apache always appends the original query string (?query=test) to the resulting URL which we don't want in this example. If you're using Apache 2.4 or later you can use the QSD option (qsdiscard) to remove the query string like this:

RewriteCond %{QUERY_STRING} ^query=test$  
RewriteRule ^/$ /noqueries [QSD,R=301,L]  

However if you're using an earlier version of Apache (like 2.2) this solution won't work. We have to use a little trick to make this happen:

RewriteCond %{QUERY_STRING} ^query=test$  
RewriteRule ^/$ /noqueries? [R=301,L]  

Notice that instead of setting the QSD option we added the question mark to the result URL. This generates the URL we wished for (http://www.example.com/noqueries) adding a new (empty) query string. The original query string is completely discarded. Have fun url-rewriting ;-)

comments powered by Disqus