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

Time:01-05

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?

CodePudding user response:

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

CodePudding user response:

Use RewriteCond before RewriteRule

RewriteCond documentation

Something like this:

RewriteCond %{REQUEST_URI} !^/secret/example.php$
RewriteRule secret /home.html
  •  Tags:  
  • Related