L
L
Let_peace2020-08-25 00:22:29
PHP
Let_peace, 2020-08-25 00:22:29

How to prevent a user from accessing php, json files via .htaccess so that ajax requests work?

I googled, but each answer is radically different from the previous one, so I can't figure it out in any way.

There are some php and json files that should not be available to the user (following a direct link, for example, http::/site.ru/file.php ), but at the same time they should accept ajax requests from the js script (in in particular $.post ).

I tried to create a separate folder for "invalid" files and throw .htaccess there:

<FilesMatch ~ "\.(php|htm|html|json)$">
  Order allow,deny
  Deny from all
</FilesMatch>

But when an ajax request was made to the necessary files, a 500 error was thrown.

Tell me, please, how to implement it correctly through .htaccess?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Shumov, 2020-08-25
@Let_peace

Actually, not at all. The user is a browser, the browser must access the script through Ajax. Ajax is essentially a direct request. You can play around with CORS, but the result will be zero because it will not save you from this.
It is worth considering what problem you are trying to solve with this. What is this script and why should it be restricted?

N
nokimaro, 2020-08-25
@nokimaro

.htaccess

SetEnvIfNoCase X-Requested-With XMLHttpRequest ajax
Order Deny,Allow
Deny from all
Allow from env=ajax

and put it in a separate folder like /ajax/ along with those scripts and files to which access is allowed only through XHR requests

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question