如何使用mod_rewrite将index.php(和其他有效的默认文件)重写到文档根目录?

我想redirectindex.php,以及任何其他有效的默认文件(如index.html,index.asp等)的文件根(其中包含index.php),像这样的东西:

RewriteRule ^index\.(php|htm|html|asp|cfm|shtml|shtm)/?$ / [NC,L] 

但是,这当然给了我一个无限的redirect循环。 什么是正确的方法来做到这一点

如果可能的话,我希望在开发和生产环境中都有这个工作,所以我不想指定一个明确的URL,比如http://www.mysite.com/作为目标。

谢谢!

如果有人发现这一点,这是我如何使用它的生产和发展。

 # index.php to root RewriteCond %{HTTP_HOST} ^localhost [NC] RewriteRule ^index\.(php|htm|html)/?$ /SiteFolder/ [R=301,NC,L] RewriteCond %{HTTP_HOST} !^localhost [NC] RewriteRule ^index\.(php|htm|html)/?$ / [R=301,NC,L] 

根据需要添加扩展名,用|分隔

觉得像这样的东西应该工作。 跑到会议,所以我没有时间来testing它,但基本上你必须设置条件不redirect主要www.site.com/index.php

 RewriteEngine On RewriteCond !^/index.php RewriteRule ^index\.(php|htm|html|asp|cfm|shtml|shtm)/?$ / [NC,L] 

你可以尝试301redirect它。 这应该是理论上search引擎友好。

 RewriteRule ^index\.(php|htm|html|asp|cfm|shtml|shtm)/?$ / [R=301,L] 

我确信Karol的解决scheme是正确的(RewriteCond在solefald的解决scheme中是不必要的),并且尊重TMG对PageRank的反驳。

首先,search引擎优化和PageRank:虽然马特卡茨已经表明,301redirect页面不像直接链接那么强大,但是这里需要纠正的情况涉及到重复的内容。 如果使用/index.php的网站和/结果在同一页面的网站,这是重复的内容,并且(尤其是与网站的主页)是一个重要的考虑因素:给定的页面应该始终有一个url,即网页的“规范”url。

最好的情况下,谷歌将忽略它决定它应该。 在最坏的情况下,它将索引两个链接到一个变体的网站将通过PR到该变体,而那些链接到另一个将通过他们的PR到另一个。 你应该把所有的页面链接到一个(而且应该是/)。

上面的Karol解决scheme是正确的(你不需要一个RewriteCond)和一个小logging:如果你正在编辑一个.htaccess文件,这是正确的写作; 如果您在服务器configuration文件或VirtualHost上下文中进行编辑,则需要先添加一个斜杠

 RewriteRule ^/index\.(php|htm|html|asp|cfm|shtml|shtm)/?$ / [R=301,L] 

或者使这个工作在任何情况下,使用? 正则expression式运算符说“可能是一个斜线”:

 RewriteRule ^/?index\.(php|htm|html|asp|cfm|shtml|shtm)/?$ / [R=301,L] 

最后一点:确保至less在你指定的configuration(服务器,虚拟主机或.htaccess)中:

 DirectoryIndex index.php