.htaccess - 301 redirect if no query string present

我们两清 提交于 2019-12-21 23:57:36

问题


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]


来源:https://stackoverflow.com/questions/11210412/htaccess-301-redirect-if-no-query-string-present

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!