How to password protect development and staging sites with .htaccess
It's easy to password protect your development and staging sites using .htaccess. But, when you're working with multiple environments and have .htaccess in your source control repository (like Git or SVN), it's a little trickier.
I think most developers understand it's a good practice to password protect development and staging sites. It keeps the public from seeing work in progess and prevents search engines from dinging you for duplicate content. We prefer to use .htaccess for setting up the password because it's lightweight and doesn't interfere with any member logins that might be native to your CMS or app.
If you're not including .htaccess in your source code repository, it's trivial to add the password requirement on your development and staging sites, but exclude it from the production site.
The issue we ran into was when we wanted to include the .htaccess file in our Git repository. We wanted that file to be in Git because it can contain some important configurations like PHP settings and redirects. But, if the .htaccess file is in Git, that means it has to be the same file for every environment.
So, how do you have a single .htaccess file that password protects one environment, but not another? Like this.
SetEnvIf Host staging.domain.com passreq AuthType Basic AuthName "Password Required" AuthUserFile /full/path/to/.htpasswd Require valid-user Order allow,deny Allow from all Deny from env=passreq Satisfy any
To use this on your site, change staging.domain.com in line #1 to the full domain name of your development or staging site and set the full path to your .htpasswd file on line #4.
Lines #6-8 is where the magic happens. It basically says, allow anyone to access the site unless the hostname matches your development site's domain.