Remove any query string from the homepage only
In .htaccess
you can use mod_rewrite to redirect all requests that contain any query string. Try the following:
RewriteEngine On
RewriteCond %{QUERY_STRING} .
RewriteRule ^$ /? [R,L]
Like the example given in the question, this only redirects requests that are for the document root / homepage. (ie. not a URL of the form: example.com/something?id=1
).
The RewriteCond
directive checks that the query string has at least 1 character (ie. the regex .
).
The query string is "removed" by appending an empty query string in the substitution string (the trailing ?
). The ?
is not present in the redirect response.
If you require this redirect to be permanent, then change the R
flag to read R=301
, otherwise it will default to a 302 (temporary) redirect.
More generic, any URL-path
If you want a more generic solution to remove the query string from any URL-path then you can change the RewriteRule
directive to the following (keeping the same RewriteCond
directive as above):
RewriteRule ^ %{REQUEST_URI} [QSD,R=302,L]
Now, a request for example.com/anything?something
will be redirected to example.com/anything
.
This also uses the QSD
(Query String Discard) flag (Apache 2.4) to remove the query string instead of appending an empty query string, as is required on Apache 2.2 and earlier (first example).
Edge case - empty query string
A minor caveat with the directives above, is that a present, but otherwise empty query string (eg. a URL-path with a trailing ?
) is not removed. For example, given a request of the form example.com/?
then the trailing ?
will remain, since the query string is strictly "empty" (and the above condition fails to match).
If you specifically wanted to cache this edge case as well then you could match against THE_REQUEST
in the RewriteCond
directive instead. For example:
RewriteCond %{THE_REQUEST} \?
RewriteRule ^ %{REQUEST_URI} [QSD,R=302,L]
The condition simply checks for an unencoded ?
anywhere in the URL.