Let's say I have /secret/example.php
In my .htaccess file I want to rewrite requests to /secret
to /home.html
using
RewriteRule secret /home.html
But now when I try to access /secret/example.php
using ajax from example.js
var xhr = new XMLHttpRequest();
xhr.open('GET', '/secret/example.php', true);
xhr.onload = function(){
console.log(xhr.responseText);
}
xhr.send();
It is also redirected and does not work.
Is there a way I can only rewrite requests made by the user (by typing www.example.com/secret
in the search bar) and still allow ajax to access the file?
My Answer:
Yes, you can achieve this by checking the `X-Requested-With` header in your .htaccess file. The `X-Requested-With` header is typically set by AJAX requests, so you can use this header to differentiate between AJAX requests and regular user requests.
Here's an example of how you can modify your .htaccess file to only redirect user requests and allow AJAX requests to access the file:
RewriteEngine On
RewriteCond %{HTTP:X-Requested-With} !XMLHttpRequest
RewriteRule secret /home.html
With this configuration, the RewriteRule will only be applied if the `X-Requested-With` header is not set to `XMLHttpRequest`, which is typically the case for AJAX requests. This way, user requests to /secret will be redirected to /home.html, but AJAX requests will still be able to access the file at /secret/example.php.
Rate this post
5 of 5 based on 3168 votesComments