htaccess将index.php重定向到root(包括子域)

Ale*_*lex 29 apache mod-rewrite

我正在尝试将index.php文件重定向到root /,我已经搜索过并发现了几个类似于以下代码的代码片段:

RewriteCond %{THE_REQUEST} ^.*/index.php 
RewriteRule ^(.*)index.php$ http://www.domain.com/$1 [R=301,L] 
Run Code Online (Sandbox Code Playgroud)

但是,这不适用于子域,例如:

  1. 我有一个子域名:subdomain.domain.com
  2. 用户访问http://subdomain.domain.com/index.php
  3. 使用上面的htaccess,它们被重定向到http://www.domain.com/而不是http://subdomain.domain.com/

有谁知道如何调整上面的htaccess所以它会考虑子域并将它们重定向到适当的位置?

例如,如果用户访问http://subdomain.domain.com/index.php,他们将访问http://subdomain.domain.com/

奖励积分:

是否有可以将此规则应用于所有文件夹的htaccess?

所以对于任何带有index.php的文件夹,它们只会重定向到它的根目录,例如http://subdomain.domain.com/folder1/folder2/index.php会自动转到http://subdomain.domain.com/folder1 /文件夹2 /

Thi*_*key 78

做这个:

RewriteCond %{THE_REQUEST} ^.*/index\.php 
RewriteRule ^(.*)index.php$ /$1 [R=301,L] 
Run Code Online (Sandbox Code Playgroud)

  • 这很好,谢谢!对于有相同问题的任何人,如果您有子域,则可能会被迫选择要放置它的文件夹,请确保从public_html中创建/选择一个文件夹,否则此htaccess会尝试将其重定向到该文件夹​​。例如,我有subdomain.domain.com,它的文件存储在www.domain.com/subdomain中,只要用户访问subdomain.domain.com/index.php,此htaccess就会将用户发送到subdomain.domain.com/subdomain,但是如果您将文件夹放在public_html之外,就不会出现此问题。 (2认同)

cai*_*005 15

我根据@ ThinkingMonkey的答案编写了以下代码

RewriteRule ^(.*)index\.(php|html?)$ /$1 [R=301,NC,L]
Run Code Online (Sandbox Code Playgroud)

它将以index.php,index.htmindex.html结尾的URI重定向到/.也适用于子目录.

另外,请注意NC标志.它使它不区分大小写.因此,即使URI是大写的,例如INDEX.PHP,它也能工作.