Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

php - Deny ajax file access using htaccess

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.

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$
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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Bad: Apache :-(

X-Requested-With in not a standard HTTP Header.

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. :-(

The Ugly: Script :-(

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.

The Good: auto_prepend_file :-)

  • But ... there's a simple trick to solve it :-)

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.

So create a .htaccess in ajax folder

php_value auto_prepend_file check.php

and create check.php as you want:

<?
if( !@$_SERVER["HTTP_X_REQUESTED_WITH"] ){
        header('HTTP/1.1 403 Forbidden');
        exit;
}
?>

You can customize it as you want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...