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:

http://example.com/file.php?q=foo&lang=en

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

http://example.com/file.php?q=foo
that you want to redirect to another URL say
http://example.com/foo.html
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$ http://example.com/foo.htm? [R,L]
The rule above will redirect
http://example.com/file.php?q=foo
to
http://example.com/foo.htm .
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$ http://example.com/file.html? [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$ http://example.com/foo.htm? [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 http://example.com/file.html?q=foo .

Hope this was helpful.
Thanks for reading!

Post a Comment

0 Comments