Search code examples
phpapache.htaccess

htaccess - Block access to php files for users while allowing javascript to access


In my main folder of my website, I have coded several php files which are meant for javascript to perform AJAX. As a result, a user shouldn't be able to access those php file.

In order to do this, I have created the following .htaccess file

DirectoryIndex test.php
<Files "database.ini">  
Order Allow,Deny
Deny from all
</Files>

<Files "*.php">
require all denied
require host xxx.com # website address
require ip xxx.xxx.xxx.xxx # server ip
</Files>

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [L]

</IfModule>

However, when I try to run my website, it tells me that the server can't access the php file in the error message displayed in the console. If I remove the <Files "*.php> block, everything works fine but that means everybody can access the php files as well.

I am not sure where I did wrong. I am not very familiar with the syntax, so I am just trying to follow the resource I found online.


Solution

  • As the JavaScript runs in the user's browser, there is no way to restrict the user from opening the same resource directly.

    If the JavaScript in the user's browser can read the resource, so too can the user.

    Any measure taken would be security by obscurity at best, like limiting the HTTP method or referrer etc. The call of the JavaScript can always be visible in the browser debug and the resulting query and content can be inspected.