Is it possible to conditionally call AddHandler in the .htaccess under Apache (2.x)?

My present situation requires that a certain AddHandler is needed by one production server but that one breaks the development server. This requires to have 2 versions of .htaccess which is pain. So, instead I would like to wrap one AddHandler within a conditional. Something of this sort:

AddHandler type/foo .ext

The problem is new but out of my control for now. I know this is far from ideal and the servers used to match 100% as they should but temporarily they cannot.


Use mod_rewrite and the H= flag. In .htaccess, use a - as the substitution if you set H= in a flag. You can then do your IP checks in a RewriteCond.

Here's some (untested!) code to accomplish this:

# Standard preamble for using mod_rewrite in a root .htaccess file:
RewriteEngine On
RewriteBase /
Options +FollowSymLinks

# Handle .ext files as type/foo if the server address is
RewriteCond %{SERVER_ADDR} =
RewriteCond %{SCRIPT_FILENAME} \.ext$
RewriteRule ^ - [H=type/foo]
  • +1, excellent suggestion. I edited your answer to add a code example; I didn't test it, though, so any errors in it should be blamed on me. – Ilmari Karonen Jun 26 '12 at 12:21

Unfortunately, Apache has very limited support for conditional configurations. Aside from specific modules that have conditional evaluations internally, such as mod_rewrite, you're limited to <IfDefine>, <IfModule>, and I believe there's also a way to enable directives based on the existence of a file or directory.

IfDefine allows you to enable configurations based on variables defined at startup via -D, e.g.

httpd -Dstaging

Or you can use Define:

Define staging staging

Unfortunately, IfDefine only evaluates whether the variable is defined, not its value. Though you can't really conditionally define it within your configurations anyway, so it's not much of a loss.

So if you have different modules enabled on your production and staging servers, or if you start your staging server with a custom config variable, then that would be your solution.

Otherwise, I suppose we'll have to wait for the day when someone creates a mod_if that lets us do:

DefineIf Server_Addr "127\.0\.0\.1" env=staging:production

<If env=staging>
   AddHandler foo-handler .foo

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.