Conditionally set an Apache environment variable

Posted by Tom McCarthy on Server Fault See other posts from Server Fault or by Tom McCarthy
Published on 2010-05-21T13:21:29Z Indexed on 2010/05/21 13:32 UTC
Read the original article Hit count: 261

Filed under:
|
|

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 the regular expression could get ugly. Also, if I want to allow another request attribute to affect the REQUEST_TYPE (e.g. if Remote_Addr = 192.168.1.[100-150] then REQUEST_TYPE = 5) then my current method of assigning a default value (i.e. using the regular expression with a negative lookahead) probaby won't work.

© Server Fault or respective owner

Related posts about apache

Related posts about setenv