Question: Rewrite from any query string after root to root in .htaccess


Rewrite from any query string after root to root in .htaccess

Answers 2
Added at 2017-01-04 18:01

I need my site to redirect all URLs with a parameter to a clean path:



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.

nr: #1 dodano: 2017-01-04 18:01

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.

nr: #2 dodano: 2017-01-04 18:01

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. (ie. not a URL of the form:

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.

Source Show
◀ Wstecz