Dynamic authentication realms in Apache

Solution 1:

Ok, here's a quick and (very) hacky way to do this. Short story is, there isn't a way (that I know of) to dynamically do what your asking with the standard Apache tools. Extra modules or code is necessary. Someone out there may have already made a module that does what you want. I didn't go looking.

Install and enable mod_perl in your Apache config, then put this block anywhere in your config after the LoadModule for perl. It doesn't have to be in any VirtualHost or Directory or anything like that.

<Perl>
 use Apache2::ServerUtil qw//;
 use Apache2::RequestRec qw//;
 use Apache2::RequestUtil qw//;
 use Apache2::Const qw/OK DECLINED/;

 my $s = Apache2::ServerUtil->server;

 $s->push_handlers(PerlHeaderParserHandler => sub { my($r) = @_;
  if ( $r->hostname eq 'www.example.com' &&
       $r->uri =~ m|^/(monitor\d+)/$| ) {
   my $monitorDirectory = $1;

   eval{$r->add_config([
    "AuthType basic",
    "AuthName 'secret $monitorDirectory'",
    "AuthUserFile /path/to/user/file",
    "require user $monitorDirectory"
   ])};
   if ( $@ ) { warn $@ }

   return OK;

  } else {
   return DECLINED;
  }
 });
</Perl>

Basically what this is doing is looking at the url of every request and if it is matches, inserting some config rules on the fly before the authentication and authorization stage of the request. To modify it, change the www.example.com bit, the regex match ^/(monitor\d+)/$, and the list of directives to insert.

This will leave you with a user file to maintain, where the username is the directory name from the url. If you want multiple users per directory, you'll have to use groups and maintain that file as well. For that, change require user $monitorDirectory to require group $monitorDirectory and add AuthGroupFile /path/to/group/file.