阻止访问包含文件

时间:2013-01-31 11:58:05

标签: php .htaccess

我遇到.htaccess文件重写规则的问题。我想在我的根目录中有一个.htaccess文件,并在那里有规则阻止人们直接通过浏览器访问文件。所以,例如我有文件夹blah / includes / file.php和.htaccess文件是在blah /文件夹中,我想阻止人们只能输入浏览器blah / includes / file.php并获取该文件,但是我也希望我在应用程序中的功能能够使用这些文件。我知道他们几乎不可能知道我的包含文件的确切名称,但我想确定。 提前谢谢。

这是我的代码没有响应:

<IfModule mod_rewrite.c>
    ## Enable Mod Rewrite, this is only required once in each .htaccess file
    RewriteEngine On
    RewriteBase /
    ## Test for access to includes directory
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /includes/ .*$ [NC]
    ## Test that file requested has php extension
    RewriteCond %{REQUEST_FILENAME} ^.+\.php$
    ## Forbid Access
    RewriteRule .* - [F,NS,L] 
</IfModule>

注意:我正在localhost中测试,如果这可能很重要。

2 个答案:

答案 0 :(得分:1)

问题出现在第一个RewriteCond中,你在/ includes /之后有空格,这会引发错误。

但是:我不会使用%{THE_REQUEST},因为它包含HTTP请求(请参阅http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritecond)。请改用%{REQUEST_URI}

因此,如果您想禁止访问/<folder>/include/*.php,则可以使用此代码:

 <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_URI} ^/[^/]+/includes/.*\.php$ [NC]
    RewriteRule .* - [F,NS,L]
 </IfModule>

假设你的.htaccess位于blah /文件夹中。

答案 1 :(得分:0)

最快捷的方法就是在包含目录中添加一行 .htaccess 文件:

deny from all

另一种方法是将包含文件夹放在您可通过网络访问的目录之外。

/home/
    /username/
        /includes/
        /public_html/
            /index.php

如果仍然想要使用RewriteRule,那么这就是你要使用的那个:

RewriteRule ^includes/ - [F,L,NC]

哪会返回401 Forbidden响应,尝试访问以includes开头的URI。