首页 > 解决方案 > 阻止除一个目录中的 php 文件

问题描述

我试图阻止对特定文件夹和子文件夹中的 php 文件的所有调用,但一个特定文件夹及其子文件夹除外。

我已经尝试了许多不同的正则表达式排列,我可以让正则表达式正确匹配,它在我遇到问题的 htaccess 中实现。

这是现在的 htaccess 文件:

<FilesMatch "\.(?i:php)$">
  <IfModule !mod_authz_core.c>
    Order allow,deny
    Deny from all
  </IfModule>
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
</FilesMatch>

这是在 htaccess 之外正确匹配的正则表达式:

^(?!.*(thedirectory)).*(?i:php)$

当我对照 index.php 检查该正则表达式时,它匹配。当我检查 /thedirectory/index.php 它不匹配。当我检查 /someotherdirectory/style.css 时,它不匹配。

我希望它如何工作是:

domain.com/folder/index.php -> 404 Error
domain.com/folder/thedirectory/index.php -> resolves
domain.com/folder/someotherdirectory/index.php -> 404 Error
domain.com/folder/someotherdirectory/afunction.php -> 404 Error
domain.com/folder/someotherdirectory/style.css -> resolves

标签: phpregex.htaccess

解决方案


结果比我想象的要简单得多:

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /
    RewriteCond %{REQUEST_URI} ^(?!.*(thedirectory)).*(?i:php)$ [NC]
    RewriteRule "(.*)" /404.php
</IfModule>

推荐阅读