How to redirect a URL with Query String apache htaccess

In this post we will learn how to redirect a URL with query string using RewriteRule directive in htaccess.
Query string represents URL part that is after ? character in URL.
A URL with query string looks like the following example URL:

As you can see the above example URL contains a querystring q=foo&lang=en with query keys and values.
Anything after ? in URL is part of QueryString. Apache mod-rewrite has a nice method to test such URLs . In mod rewrite you can match against your Query String URL using %{QUERY_STRING} in RewriteCond .
%{QUERY_STRING} variable contains the full URL querystring starting with the first query key ie q=foo&lang=en . You can use a regular expression based pattern to dynamically match against query key and value.

Redirect query string using htaccess

Let's see a real world example of Query string URL redirection.
Assuming you have a perticular URL
that you want to redirect to another URL say
you will use a redirect logic in htaccess that first checks the QUERY_STRING and if it exists in URL then your RewriteRule will redirect it.

RewriteEngine on
RewriteCond %{QUERY_STRING} ^q=foo$ [NC]
RewriteRule ^file.php$ [R,L]
The rule above will redirect
to .
We use RewriteCond directive to test the URL querystring so that the rule can apply only to this specific QUERY_STRING. If your query value q=foo is dynamic you could use regex catch all pattern .+ in the test string of RewriteCond.
Many new users often make a mistake when writing a rule for Query string URL. They write the full URL path including querystring in RewriteRule like the following:

RewriteEngine on
RewriteRule ^file.php\?q=foo$ [L,R]
The rule above will never redirect /file.php?q=foo because you can test or use QueryString like that. The pattern of a RewriteRule matches the URL path only ie /file.php and the QUERYSTRING part isnt checked. The right rule to redirect the above URL is :

RewriteEngine on
RewriteCond %{QUERY_STRING} ^q=foo$ [NC]
RewriteRule ^file.php$ [R,L]
We use ? an empty question mark at the end of the destination path or URL to remove the old querystring. Otherwise if you don't use ? then the above rule will append the old querystring q=foo to the new URL . Your new URL will then look something like .

Hope this was helpful.
Thanks for reading!

Post a Comment