嗨,我是网络编程的新手。我正在开发一个带有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文件。此外,我会通过网址重写“隐藏”.php文件(例如,而不是服务mysite.org/accounts.php
我将提供mysite.org/accounts
,但不仅仅是删除.php扩展名,而是重定向mysite.org/accounts
到一个名为youwillneverknowthis.php
)的文件。
提前致谢。
学家
答案 0 :(得分:-2)
html
目录中,因为它可以通过互联网访问。包含私有代码的文件应从该目录中删除。将它们放在私人目录中,例如/var/www/php/src
和var/www/php/app
现在您希望用户能够在不暴露敏感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;
您的下一个问题是关于网址重写,以便mysite.org/accounts
可以重定向到youwillneverknowthis.php
)。将名为.htaccess
的文本文件放在公共文档根目录var/www/html
中。添加以下规则(每行一条规则):RewriteEngine on
。这会打开网址重写
RewriteRule ^accounts$ gateway.php?dir=src&file=youwillneverknowthis.php [QSA,L]
根据需要调整目录和文件参数。这会将用户重定向到gateway.php,然后在幕后读取并执行私有代码。 Query String Append [QSA]标志确保将任何预先存在的查询参数与gateway.php
和dir
参数一起传递给file
。 [L]标志使重写引擎知道在找到匹配项时停止处理和重定向。希望有所帮助。
编辑:通过清理输入来提高安全性