BeetleJuice BeetleJuice - 1 year ago 276
Apache Configuration Question

htaccess If...Else always selects Else

I set an environment variable in httpd-vhosts.conf


I try setting special rules based on its value in .htaccess

<If "%{ENV:EARLY_VAR} == '1'">
SetEnv TEST_VAR if_branch
SetEnv TEST_VAR else_branch

I expect
environment var to equal
. In PHP

var_dump(getenv('EARLY_VAR')); // string '1'
var_dump(getenv('TEST_VAR')); // string 'else_branch'

I also tried setting
above the If/Else, both using
. Always the Else branch is executed.

Why is this?

Apache 2.4

Answer Source

Without using expression i.e. if/else directives you can do this:

# set EARLY_VAR to 1
SetEnvIf Host ^ EARLY_VAR=1

# if EARLY_VAR is 1 then set TEST_VAR to if_branch
SetEnvIf EARLY_VAR ^1$ TEST_VAR=if_branch

# if EARLY_VAR is NOT 1 then set TEST_VAR to else_branch
SetEnvIf EARLY_VAR ^(?!1$) TEST_VAR=else_branch

This will work with even older Apache versions i.e. <2.4


In your Apache config or vhost config have this variable initialization:

SetEnvIf Host ^ EARLY_VAR=5

Then in your .htaccess you can use:

<If "env('EARLY_VAR') == '5'">
   SetEnv TEST_VAR if_branch
   SetEnv TEST_VAR else_branch

Reason why you need env variable declaration in Apache/vhost config because .htaccess is loaded after Apache/vhost config and env variables set in same .htaccess are not available for evaluation in if/else expressions.

Also, note that it is important to use SetEnvIf instead of SetEnv to make these variables available to if/else expressions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download