.htaccess SetEnv Conditionals: mod_setenvif

The mod_setenvif module allows you to set environment variables according to whether different aspects of the request match regular expressions you specify.

via mod_setenvif – Apache HTTP Server.

I’ve never claimed to be a server guru, and I’ve never had much interest in delving into Apache configuration files, but web programming almost request that I dig down and learn about what I’m using in order to make the best use of the technologies I’m using. Besides, I’m well past the point where I can keep making excuses for not learning Apache.

Zend Framework 1.10 uses the .htaccess file to set the enviromental variable APPLICATION_ENV. It does this using SetEnv.

SetEnv APPLICATION_ENV production

This let’s us set the environment to production or development, obviously. The idea is that you can set the variable depending on where the files are: a production server or a development server.

However, I wanted something a bit simpler at the moment. I wanted to the variable based on the URL used. beta.example.com would get the development site, and www.example.com would load up the production site. Both sites share the same directory as their web directory, but I want the live site to display a ‘Coming soon…” message, while the beta site would let me work. I’m not concerned with people getting access to beta, and the only difference will be the display of the default page, but it’s a simple thing. Now, I could have done this in PHP, but I didn’t want to do this. At the same time, I had in mind the ability to use this setting of environmental variables something I could use for other things, like debugging, web services, and what not. Being able to let Apache handle this, and then letting Zend build the configuration based on this setting, would let me not worry about programing any of this logic into my system. I just program away, and I can make the assumption that whatever happens based on the URL will happen appropriately.

Anyways, a quick check of the docs for SetEnv lead me to discover SetEnvIf. I’ve seen this before, but I never paid much attention to this setting. It’s rather simple, and could be very powerful.

As a simple example, I want to set the APPLICATION_ENV variable to production if the website is www.example.com, and development if the site is beta.example.com. This worked:

SetEnvIf Host "www.example.com" APPLICATION_ENV=production
SetEnvIf Host "beta.example.com" APPLICATION_ENV=development

That was the initial code.  Of course, after reading through the manual, I read about SetEnvIfNoCase, which is the same as SetEnvIf, except the “matching is performed in a case-insensitive manner.”

SetEnvIfNoCase Host "www.example.com" APPLICATION_ENV=production
SetEnvIfNoCase Host "beta.example.com" APPLICATION_ENV=development

Pretty simple.