Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 5 down vote accepted

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
share|improve this answer
    
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. –  Tom McCarthy May 21 '10 at 14:14

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.