3

I would like to conditionally set the value of an Apache2 environment variable and assign a default value if one of the conditions is not met. This example if a simplification of what I'm trying to do but, in effect, if the subdomain portion of the host name is hr, finance or marketing I want to set an environment var named REQUEST_TYPE to 2, 3 or 4 respectively. Otherwise it should be 1. I tried the following configuration in httpd.conf:

<VirtualHost *:80>
  ServerName     foo.com
  ServerAlias    *.foo.com
  DocumentRoot   /var/www/html

  SetEnv REQUEST_TYPE 1
  SetEnvIfNoCase Host  ^hr\.         REQUEST_TYPE=2
  SetEnvIfNoCase Host  ^finance\.    REQUEST_TYPE=3
  SetEnvIfNoCase Host  ^marketing\.  REQUEST_TYPE=4
</VirtualHost>

However, the variable is always assigned a value of 1. The only way I have so far been able get it to work is to replace: SetEnv REQUEST_TYPE 1 with a regular expression containing a negative lookahead: SetEnvIfNoCase Host ^(?!hr.|finance.|marketing.) REQUEST_TYPE=1

Is there a better way to assign the default value of 1? As I add more subdomain conditions, or if I allow another request attribute to affect the REQUEST_TYPE (e.g. if Remote_Addr = 192.168.1.[100-150] then REQUEST_TYPE = 5), the regular expression with the negative lookahead could get ugly and hard to manage.

1 Answer 1

7

So it appears it isn't possible to reassign an environment variable. But you can test if the variable is set, if not, set it to the default value.

SetEnvIfNoCase Host            ^hr\.         REQUEST_TYPE=2
SetEnvIfNoCase Host            ^finance\.    REQUEST_TYPE=3
SetEnvIfNoCase Host            ^marketing\.  REQUEST_TYPE=4
SetEnvIf       REQUEST_TYPE    ^$            REQUEST_TYPE=1
1
  • Awesome. That's the solution I was looking for. I previously tried something similar -- <IfDefine REQUEST_TYPE> ... -- but found that IfDefine doesn't test environment variables. May 21, 2010 at 14:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .