-1

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.

Yan Zhuang
  • 436
  • 3
  • 10
  • Take a look at an [answer](https://stackoverflow.com/questions/33999475/prevent-direct-url-access-to-php-file/33999539#33999539) I gave a few years ago - I think it'll help – Professor Abronsius Mar 20 '21 at 07:41
  • @ProfessorAbronsius Thanks. I have tried that, however there is a problem. Now when javascript tries to get information from the php file, it indicates a 302 found and redirects to another page that I specified in `die(location('......'))`. Therefore my javascript was not able to retrieve the data. I copied the code that you did, not sure if I need to change something? – Yan Zhuang Mar 20 '21 at 18:00

1 Answers1

1

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.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103