Is it possible to detect an ajax request with Apache 2.4 for a mod_rewrite rule?

Is it possible?

Trying to move my script security to the server-level.

With PHP, just check if $_SERVER['HTTP_X_REQUESTED_WITH'] is set to XMLHttpRequest (jQuery added).

I guess maybe a better question is, how can I add the X-Requested-With request header to a variable I can check with a mod_rewrite RewriteCond?


If you are setting the X-Requested-With HTTP request header as part of the "AJAX request" (as would be implied if you are seeing $_SERVER['HTTP_X_REQUESTED_WITH'] in PHP) then you can check this header directly with mod_rewrite.

For example, to serve a 403 Forbidden for any requests to the /scripts/ directory that do not have an X-Forwarded-With HTTP header set to XMLHttpRequest:

RewriteEngine On

RewriteCond %{HTTP:X-Requested-With} !=XMLHttpRequest
RewriteRule ^/?scripts/ - [F]