使用 htaccess 拒绝 ajax 文件访问 [英] Deny ajax file access using htaccess
问题描述
有些脚本我只通过 ajax 使用,我不希望用户直接从浏览器运行这些脚本.我使用 jQuery 进行所有 ajax 调用,并将所有 ajax 文件保存在名为 ajax 的文件夹中.
There are some scripts that I use only via ajax and I do not want the user to run these scripts directly from the browser. I use jQuery for making all ajax calls and I keep all of my ajax files in a folder named ajax.
所以,我希望创建一个 htaccess 文件来检查 ajax 请求 (HTTP_X_REQUESTED_WITH) 并拒绝该文件夹中的所有其他请求.(我知道可以伪造 http 标头,但我想不出更好的解决方案).我试过这个:
So, I was hoping to create an htaccess file which checks for ajax request (HTTP_X_REQUESTED_WITH) and deny all other requests in that folder. (I know that http header can be faked but I can not think of a better solution). I tried this:
ReWriteCond %{HTTP_X_REQUESTED_WITH} ^$
ReWriteCond %{SERVER_URL} ^/ajax/.php$
重写规则 ^.*$ -[F]
ReWriteCond %{HTTP_X_REQUESTED_WITH} ^$
ReWriteCond %{SERVER_URL} ^/ajax/.php$
ReWriteRule ^.*$ - [F]
但是,它不起作用.我做错了什么?有没有其他方法可以达到类似的结果.(我不想检查每个脚本中的标题).
But, it is not working. What I am doing wrong? Is there any other way to achieve similar results. (I do not want to check for the header in every script).
推荐答案
The Bad: Apache :-(
X-Requested-With
不是标准的 HTTP 标头.
您根本无法在 apache 中读取它(也不是通过ReWriteCond %{HTTP_X_REQUESTED_WITH}
也不由%{HTTP:X-Requested-With}
),所以不可能在 .htaccess 或同一个地方检查它.:-(
You can't read it in apache at all (neither by
ReWriteCond %{HTTP_X_REQUESTED_WITH}
nor by
%{HTTP:X-Requested-With}
), so its impossible to check it in .htaccess or same place. :-(
它只能在脚本中访问(例如 php),但您说由于文件数量的原因,您不想在所有脚本中包含一个 php 文件.
Its just accessible in the script (eg. php), but you said you don't want to include a php file in all of your scripts because of number of files.
- 但是......有一个简单的技巧可以解决它:-)
auto_prepend_file
指定在主文件之前自动解析的文件的名称.您可以使用它来自动包含检查器"脚本.
auto_prepend_file
specifies the name of a file that is automatically parsed before the main file. You can use it to include a "checker" script automatically.
于是在ajax文件夹中创建一个.htaccess
So create a .htaccess
in ajax folder
php_value auto_prepend_file check.php
并根据需要创建check.php
:
<?
if( !@$_SERVER["HTTP_X_REQUESTED_WITH"] ){
header('HTTP/1.1 403 Forbidden');
exit;
}
?>
您可以根据需要对其进行自定义.
You can customize it as you want.
这篇关于使用 htaccess 拒绝 ajax 文件访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!