Mod_rewrite: environment variables aren’t being expanded in RewriteConds

apache-2.2mod-rewrite

I've got a RewriteCond in a .htaccess similar to:

RewriteCond "%{ENV:FOO}" =bar

But the ${ENV:FOO} is being expanded to the value of FOO, it's always blank.

For example, if I SetEnv FOO "bar" just before the RewriteCond, then crank up the RewriteLogLevel, I get this in my rewrite log:

RewriteCond: input='' pattern='=bar' => not-matched

What am I doing wrong here? How can I make environment variables expand inside of RewriteConds?

Also, if I add a silly RewriteRule like RewriteRule .* %{ENV:FOO}, I can see in the rewrite log that the variable is being correctly expanded there.

My Apache version is 2.2.17.

Edit: I've found another reference to this problem. It seems like a “solution” is to use SetEnvIf instead of SetEnv… =\

Additionally, it doesn't seem like the location of the SetEnv has any effect. I've put it both in httpd.conf and in the .htaccess, and neither work.

Best Answer

Ah, here we go. From the SetEnv documentation (under "caveats"):

The SetEnv directive runs late during request processing meaning that directives such as SetEnvIf and RewriteCond will not see the variables set with it.

So, for now, I guess I'm using:

SetEnvIf _ .* FOO=bar