Take the 2-minute tour ×
Webmasters Stack Exchange is a question and answer site for pro webmasters. It's 100% free, no registration required.

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:

IF IP=='1.2.3.4' THEN
AddHandler type/foo .ext
ENDIF

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.

share|improve this question

2 Answers 2

up vote 2 down vote accepted

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 1.2.3.4:
RewriteCond ${SERVER_ADDR} =1.2.3.4
RewriteCond ${REQUEST_FILENAME} \.ext$
RewriteRule ^ - [H=type/foo]
share|improve this answer
    
+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
</If>
share|improve this answer

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.