Conditional .Htpasswd for Multi-Environment Setups

November 8, 2009

So a while back i set Chris over at CSS-Tricks some code for his ongoing snippet library project. This is a quick explanation of that code.

You see when you are working with a multi-environment setup that is synced via a version control system such as Git or Subversion, you need a way to keep your development environments locked down while allowing access to your public environment.

Below is some text that you will input into a .htaccess file placed in your webroot

#allows a single uri through the .htaccess password protection
SetEnvIf Request_URI "/testing_uri$" test_uri

#allows everything if its on a certain host
SetEnvIf HOST "^testing.yoursite.com" testing_url
SetEnvIf HOST "^yoursite.com" live_url
Order Deny,Allow

AuthName "Restricted Area"
AuthType Basic
AuthUserFile /path/to/your/.htpasswd
AuthGroupFile /
Require valid-user

#Allow valid-user
Deny from all
Allow from env=test_uri
Allow from env=testing_url
Allow from env=live_url
Satisfy any

so in the above code the "testing_uri" part could be if i only wanted to allow this url through my htaccess protections (useful for paypal pings) ex "http://mysite.com/paypal/ipn"

The host part is to allow anyone through if they are requesting the code from a specific domain such as "testing.yoursite.com". If it is "development.yoursite.com" it will not allow the user through.

here is the code on css-tricks and here is the code as a github gist

Thanks for reading and as always comments & questions are heavily encouraged!

Monitor your DNS Zones with ZoneWatcher

Be alerted of DNS record changes moments after they happen, not from upset customers.

ZoneWatcher screenshot