拒绝访问除root index.php之外的所有.php文件

时间:2012-11-06 12:53:51

标签: regex .htaccess

这基本上是this question的副本,但有一点需要注意:我想拒绝直接访问根目录下名为index.php的所有文件。

允许: 的index.php

拒绝: /application/views/settings/index.php

我知道我可以使用PHP来查找已定义的常量或变量,但是只能使用.htaccess实现这一点吗?这就是我到目前为止所做的:

##
# Disallow direct access to files.
#

<FilesMatch "^(.*)\.php$">
    Order Deny,Allow
    Deny from all
</FilesMatch>

<FilesMatch "^index\.php$">
    Order Allow,Deny
    Allow from all
</FilesMatch>

添加第三个FilesMatch以拒绝"^(.*)/index/index\.php$"不起作用。

3 个答案:

答案 0 :(得分:2)

您无法单独使用<FilesMatch<Files>指令:您需要将它们与<Directory结合使用。例如:

<Directory /var/www>
  <FilesMatch "\.php$">
    Order Deny,Allow
    Deny from all
  </FilesMatch>
  <FilesMatch "^index\.php$">
    Order Allow,Deny
    Allow from all
  </FilesMatch>
</Directory>

<Directory /var/www/*>
  <FilesMatch "\.php$">
    Order Deny,Allow
    Deny from all
  </FilesMatch>
</Directory>

这里的问题是您应该编辑httpd.conf或类似文件,因为<Directory>指令不能在.htaccess中使用。

如果您无法更新.conf个文件并且.htaccess是唯一的方法,那么您必须在每个目录的.htaccess中复制显示的规则。是否比使用if(defined(...))技巧更好,取决于你。

答案 1 :(得分:0)

DEMO

(?<![^\/])\/index\.php

快速正则表达式,你可能想要更准确的东西。

答案 2 :(得分:0)

所以你想阻止直接调用index.php?

最流行的网络应用程序这样做的方式是,他们在某处定义一个常量,然后在他们不想直接调用的每个文件中添加对该常量的检查:

在可以直接调用的主文件中,包含其他index.php文件,执行:

define ("CAN_RUN", true);

在您不想直接调用的每个子文件中:

if (!defined("CAN_RUN")) die ("This file can't be called directly.");
相关问题