Prevent access to php files (folder) with .htacces

2019-04-16 07:27发布

问题:

I have a folder www.mysite.com/page/panel/soascripts/ where there are 10 different PHP files. I want to prevent access to the folder soascripts and the php files in it. Except X-Requested-With = XMLHttpRequest (for ajax). Is this possible with htaccess?

回答1:

In the htaccess file in your soascripts folder:

RewriteEngine On
RewriteCond %{HTTP:X-Requested-With} !=XMLHttpRequest
RewriteCond %{HTTP:X-REQUESTED-WITH} !^(XMLHttpRequest)$
RewriteRule \.php$ - [L,F]

So without the

X-Requested-With: XMLHttpRequest

request header, the response will be a 403 forbidden.


EDIT:

If you want to add the rules to the document root, you just need to include the path:

RewriteCond %{HTTP:X-Requested-With} !=XMLHttpRequest
RewriteCond %{HTTP:X-REQUESTED-WITH} !^(XMLHttpRequest)$
RewriteRule ^page/panel/soascripts/[^/.]+\.php$ - [L,F]

Make sure to add it before any type of routing rules (like stuff being sent to index.php).