通过.htaccess保护web服务器的正确方法



嗨,我是网络编程的新手。我正在开发一个带有PHP后端应用程序的网站。我使用的是Ubuntu 14.04服务器、Apache、PHP 5.5和Mysql。目前这是我在/var/www/html:下的目录结构

example.com
app/  # this dir contains the backend
src/  # this contains some common stuffs between front and back ends
web/  # this is the 'public directory' which serves the frontend

我搜索了很多关于.htaccess的内容,但我无法指出一个明确的解决方案来保护所有不在web/目录中的.php文件。此外,我会通过url重写来"隐藏".php文件(例如,我将为mysite.org/accounts服务,而不是为mysite.org/accounts.php服务,但不仅仅是删除.php扩展名,而是将mysite.org/accounts重定向到一个名为youwillneverknowthis.php的文件)。

提前谢谢。

J。

  1. 为了保护您的PHP文件,不要将它们放在公共html目录中,因为它可以通过互联网访问。包含私有代码的文件应该从该目录中取出。将它们放在专用目录中,如/var/www/php/srcvar/www/php/app
  2. 现在,您希望用户能够在不暴露敏感php代码的情况下获得"page.php"。一种解决方案是在公共目录/var/www/html中有一个名为gateway.php的脚本,该脚本在私有目录dir中查找名为file的文件并执行其内容。$_GET的值来自下面的步骤4。在需要该文件之前,请确保对输入进行消毒,以防止恶意行为者使gateway.php运行错误的脚本。例如,您可以将请求的文件与允许文件的白名单进行比较,如果不匹配,则停止执行。

    <?php #gateway.php
    if (empty($_GET['file'])):
    //the file is missing
    http_response_code(400); //bad request
    exit;
    else:
    $file = realpath(rawurlencode("/var/www/php/$_GET[dir]/$_GET[file]"));
    //SAFE_SCRIPTS is a string constant: whitelist of allowed files
    //eg:define("SAFE_SCRIPTS",'"path/to/a.php","path/to/b.php"')
    if(strpos(SAFE_SCRIPTS,$file)===false):
    //script is not in the whitelist
    http_response_code(403);//Forbidden
    trigger_error("Forbidden script: $file");
    die("Access to this resource is forbidden");
    endif;
    require $file;
    endif;
    
  3. 您的下一个问题是关于url重写,以便mysite.org/accounts可以重定向到youwillneverknowthis.php)。在公共文档根目录var/www/html中放置一个名为.htaccess的文本文件。添加以下规则(每行一条规则):RewriteEngine on。这将打开url重写

  4. 要重定向url,请添加以下规则(单行):RewriteRule ^accounts$ gateway.php?dir=src&file=youwillneverknowthis.php [QSA,L]根据需要调整dir和file参数。这将把用户重定向到gateway.php,然后它将读取并执行私有代码,所有这些都是在幕后进行的。查询字符串附加[QSA]标志确保任何预先存在的查询参数与dirfile参数一起传递给gateway.php。[L]标志使重写引擎知道在找到匹配时停止处理和重定向

希望能有所帮助。

编辑:通过清除输入来提高安全性

最新更新