I was wondering if it was possible to setup a conditional http basic auth requirement based on the virtual host URL in an .htaccess file.
For example what I want to do is have mysite.com and test.mysite.com run off the same code base in the same directory but password protect test.mysite.com. It would be setup this way so that I wouldn't need to branch my code since my app code can see which vhost/url it's being served from and pick the database to serve content from.
You can sort of kludge this by using
mod_setenvif
along with themod_auth
modules. Use theSetEnvIfNoCase
directive to set which host is password protected. You'll need a couple of extra directives to satisfy access:Then inside the
Directory
block (or just out in the open) you have your auth stuff setup, something like this:Now for the require/satisfy stuff:
This will make it so any host that doesn't match
^test\.mysite\.com\.?(:80)?$
will have access without need for auth (Allow from env=!PROTECTED_HOST
) but otherwise, we need a valid user (Require valid-user
). TheSatisfy any
ensures that we just need one of the 2, either the Allow or Require.I had problems implementing Jon's solution: Although I am quite familiar with Apache conf and regular expressions, the authentication always fired. From a quick analyzes it looked like the
Allow from env=!PROTECTED_HOST
line did not kick in.But I found another solution that actually looks safer to me:
I created two virtual hosts for the two domains pointing to the same document root (which is fully allowed by the way). In one of the vhosts I added the directives for basic auth (directly into the vhost directive block).
Works like a charm. And I have a better feeling that this is really safe - no risk to overlook any details in the regex pattern that would open up the gates for intruders.
Here's a solution similar to what Jon Lin proposed, but using
RewriteCond
to check the host name: