Reputation: 514
I need my site to redirect all URLs with a parameter to a clean path:
Have:
http://example.com/?id=1
Want:
http://example.com
Why this? I am using the share and like facebook buttons into my single page site, when you came from a link with parameter the facebook button doesn't show the cumulative likes (it treat this like a new page). So I need to redirect to clean root path to show them.
Upvotes: 1
Views: 1190
Reputation: 45914
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.
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).
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.
Upvotes: 3
Reputation: 2282
You put a PHP tag, so this is a PHP solution.
In your index.php
, you can check if there are any GET variables and redirect back to the site. This needs to be before any output is sent by the page, so it should be as close to the top of the page as possible.
if (count($_GET) > 0) {
header("Location: " . $_SERVER['PHP_SELF']);
die(); // Very important to prevent the rest of the page from executing anyway
}
You could also use header("Location: /");
if you want to make sure to hide the name of the script.
Upvotes: 0