代码之家  ›  专栏  ›  技术社区  ›  BeetleJuice

Chicken&Egg:如果.htaccess需要链接到public_html,如何将PHP排除在外?

  •  2
  • BeetleJuice  · 技术社区  · 10 年前

    我正在努力养成良好的安全习惯,所以我想将敏感的PHP文件移到public_html目录之外。我的设置是LAMP(Apache 2.4,PHP 5.5),具有以下目录结构:

    • /home/username/public_html
    • /home/username/src

    敏感文件位于 /src 。我以前的设置在 /home/username/public_html/src 我有一些.htaccess规则指导用户,比如

    RewriteRule ^myaccount$ src/account.php

    现在脚本已经脱离了public_html,我不知道如何从htaccess重定向它(htaccess中的所有路径都是相对于 /home/username/public_html )

    我读到了 Alias 来自的指令 Apache docs 这将允许我设置一个指令,例如 Alias /src /home/username/src 但这在 .htaccess 我宁愿不改变 httpd[-vhosts].conf 除非这是解决我问题的最好方法。

    溶液 credit:@Idealcastle(下图)启发了一个解决方案,允许我将敏感文件从 public_html 同时仍然允许htaccess链接到它们。

    我将.htaccess指令从 ^myaccount$ /src/account.php ^myaccount$ redirect.php?file=account.php 。然后我创建了一个网关脚本,其中包含我试图保护的脚本文件。 redirect.php 位于public_html文件夹中,内容如下:

    <?php
    if (empty($_GET['file'])):
        //the file argument is missing
        http_response_code(400); //bad request
        exit;
    else:        
        $file = rawurlencode($_GET['file']);
        $path = "/home/username/src/$file";
        //Check the file against a whitelist of approved files. if it's not
        //on the list, exit with http_response_code(403): Access Forbidden
    
        //seek the file from its private location
        require $path;
    endif;
    

    此代码将根据 file 参数设置在 .htaccess

    1 回复  |  直到 10 年前
        1
  •  3
  •   tmarois    10 年前

    您不想重定向或公开访问 /src 目录,因为它破坏了您所做的目的。

    如果我没有理解错的话,将特定文件链接到 /public_html /钢筋混凝土 用于脚本执行。

    例如 /home/username/public_html/account.php

    在这个文件中

    <?php include('/home/username/src/account.php'); ?>

    现在,公众可以访问您允许的文件 /钢筋混凝土 被保护不受直接脚本执行的影响。

    然后为了你的htaccess,做同样的事情,

    RewriteRule ^myaccount$ /home/username/public_html/account.php

    而是将其转到公共html。

    推荐文章