BeetleJuice BeetleJuice - 2 months ago 25
Apache Configuration Question

htaccess If...Else always selects Else

I set an environment variable in httpd-vhosts.conf

SetEnv EARLY_VAR 1


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

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


I expect
TEST_VAR
environment var to equal
if_branch
. In PHP

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


I also tried setting
EARLY_VAR
in
.htaccess
above the If/Else, both using
SetEnv
and
SetEnvIf
. Always the Else branch is executed.

Why is this?

Apache 2.4

Answer

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


EDIT:

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
</If>
<Else>
   SetEnv TEST_VAR else_branch
</Else>

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.

Comments