Search code examples
javascriptphpajax.htaccess

Is there a way to treat ajax requests different than user requests in .htaccess?


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?


Solution

  • It is possible if you set additional header in xhr request: xhr.setRequestHeader("VIAXHR", "true");

    Then in .htaccess something like this:

    RewriteCond %{HTTP:VIAXHR} !^true$
    RewriteRule secret /home.html