.htaccess - 301 redirect if no query string presen

2019-04-15 10:32发布

问题:

i would like to create a 301 from a page to the same page except that the destination page has a parameter in the url. Browsers show me an error (too many redirects) so its seems that there is an infinite loop. This is my code:

RewriteEngine on
Redirect 301 /index.php http://www.monsite.com/index.php?step=1

thanks to advice me for that :D

回答1:

You need to conditionalize the redirect and do it in PHP to prevent the infinite redirect loop.

index.php:

if(!isset($_GET['step'])){
    header('Location:http://www.monsite.com/index.php?step=1');
}

The way you have it configured will redirect indefinitely, since nothing is saying to the engine "don't redirect me as soon as the URL variable step is set".

There are ways to do this in the .htaccess file, but since these kind of redirects are generally application logic it seems to make more sense to do it directly in your script.

Or, for a pure .htaccess solution:

#if query string is empty

RewriteCond %{QUERY_STRING} ^$

#match on / for root, or .index.php in request and send to query string version 

RewriteRule ^(/|index.php)?$ /index.php?step=1 [R=301,L]