How to use SetEnvIf to set a variable based on the Http Host

apache-2.2

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?

Best Answer

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.

Related Topic