Sonntag, 9. August 2015

SetEnvIf Request_URI not working due to rewrite rule


The Apache HTTPD has some nice configuration options, to change its behaviour dynamically. So is the SetEnvIf module and command, which sets an environment(env) variable based on a regex match to a variable.

If you like to set a special environment variable for the URI /index.html you can easily apply

SetEnvIf Request_URI /index.html is_index

then on every call /index.html the variable is_index will be set true.
But what if you are applying a rewrite rule like

RewriteRule .* index.php [L]

What will happen to your environment variable? Will the URI /index.html be rewritten to index.php and the env variable is_index be set? Apparently not. To test this you can write the regex match to an env variable with

SetEnvIf  Request_URI (.*) match=$1

Printing this will show you /index.php for every uri you call. Why? Because you are rewriting the uri with mod_rewrite.
To set an env variable for an uri before rewriting, you have to set it during the rewrite.
A configuration for setting the env variable for index.html and rewriting everything for index.php would look like:

RewriteRule index.html index.php [E=is_index:1,L]

RewriteRule .* index.php [L]

Tool to test Mod Rewrite config http://martinmelin.se/rewrite-rule-tester/

Keine Kommentare: