【问题标题】:Preventing access to include files阻止访问包含文件
【发布时间】:2013-01-31 11:58:04
【问题描述】:

我遇到了 .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 中进行测试。

【问题讨论】:

    标签: php .htaccess


    【解决方案1】:

    问题是在第一个 RewriteCond 中 /includes/ 后面有一个空格,这会引发错误。

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

    所以,如果你想禁止访问/&lt;folder&gt;/include/*.php,你可以使用这个代码:

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

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

    【讨论】:

    • 感谢您指向该空间。但是在我更改后,我仍然可以输入包含文件夹和他的 php 文件。也尝试了你的解决方案,同样的事情。你知道那是什么吗?
    • 假设你有文件/foo/includes/file.php,上面的代码在我的开发服务器上运行良好。您的确切文件结构是什么?
    • 这是我的文件路径。php localhost/education/appFolder/include/file.php 我的 .htaccess 在我正在使用的应用程序 appFolder 中。
    • 有没有可能这与覆盖 Apache 或在线的东西有关?
    • 好的,如果有多个目录级别,它将无法工作,但您可以使用此代码,如果它符合您的需要:RewriteCond %{REQUEST_URI} /includes/.*\.php$ [NC] 这应该涵盖任何子文件夹中的每个 PHP 文件命名为“包括”。
    【解决方案2】:

    最快的方法是在你的 includes 目录中放一个单行 .htaccess 文件:

    deny from all

    另一种选择是将您的 includes 文件夹放在您的网络可访问目录之外。

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

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

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

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

    【讨论】:

    • RewriteRule ^includes [F,L,NC] 应该是RewriteRule ^includes/ - [F,L,NC],否则不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    相关资源
    最近更新 更多