11

I'm trying to set a variable on Apache

ENV=DEV if the http host is the dev URL

or

ENV=PRD if the http host is the prd URL

and then use $_SERVER['ENV'] to create some logic branches

So far none of these have worked for me and we do have the setenvif module installed

SetEnvIfNoCase Referer
SetEnvIfNoCase Remote_Host

What's the right way to do this?

15

Taking a quick look at the documentation:

The SetEnvIf directive defines environment variables based on attributes of the request. The attribute specified in the first argument can be one of three things:

An HTTP request header field (see RFC2616 for more information about these); for example: Host, User-Agent, Referer, and Accept-Language. A regular expression may be used to specify a set of request headers.

So, it's certainly possible to make an environment variable conditional on the Host header. It looks like you're trying to use either the Referer or Remote_Host headers, neither of which is exactly what you want (although in theory Referer should contain the value of the Host header in most cases). Remote_Host would be the hostname of the client making the request, which is not at all what you want (and in most configurations would simply not be available, since it's typical to have DNS lookups turned off for performance reasons).

Try something like this:

SetEnvIf Host "www-dev\.example\.com" ENV=DEV
SetEnvIf Host "www-production\.example\.com" ENV=PRD

...and then use $_SERVER['ENV'] to create some logic branches

But note also that you can simply reference the value of the Host header directly in PHP without going through this chicanery; $_SERVER['HTTP_HOST'] will have exactly what you want.

| improve this answer | |
  • Beautiful. This let me write custom rules to require passwords when connecting to certain Hosts, but not others (ie, protect the staging box when one VM is cloned onto multiple Amazon EC2 instances, but don't write custom Chef recipes). Very useful, if hard to search for, functionality. – Eric L. Feb 25 '15 at 23:05
  • 1
    The SetEnvIf docs say that the 3rd param is a regex, shouldn't the dots in the domain name be escaped with a backslash? Or does quoting the value in double quotes makes Apache treat it as a string literal? – jakub.g Feb 26 '17 at 11:18
  • @jakub.g Yes, they are a regex and should be escaped. In this case, since a dot matches any single character, a "www-dev.example.com" regex will also match unexpected Hostnames, such as www-dev-example.com. You'll get the expected matches and more. I've updated the example now. – Martijn Heemels Dec 5 '17 at 14:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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