Password protect a directory with ApachePosted in Apache -
This post is more of a self-reference than anything because there are probably fifty million other posts on the Internet showing how to password protect a directory with an Apache .htaccess file...
Password protection with .htaccess
Create a .htaccess file in the directory you want password protected. This will make all directories under that password protected as well. It should contain the following:
AuthUserFile /path/to/.htpasswd AuthName "Restricted Access" AuthType Basic require user [username]
Change /path/to/.htpasswd to the full path to the file containing the passwords (information about how to create this is below). Note that this must be the full path to the password file; relative directories do not work.
Change "Restricted Access" to whatever it is you want to appear in the password dialog that appears.
Change [username] to the username(s) from the .htpasswd file. If you want to have more than one user name listed here, separate them with spaces.
Password protection in the Apache configuration
The format is the same but the the directives need to be contained within a <Directory> or <Location> block. This can be done pretty much anywhere in the Apache configuration but the <Location> example only makes sense within a <virtualhost> block.
In the following two examples, the directory requiring protection is at /var/www/mysite/private where /var/www/mysite is the webroot.
<Directory /var/www/mysite/private> AuthUserFile /path/to/.htpasswd AuthName "Restricted Access" AuthType Basic require user [username] </Directory>
<Location /private> AuthUserFile /path/to/.htpasswd AuthName "Restricted Access" AuthType Basic require user [username] </Location>
When making these changes in the Apache configuration, Apache has to be gracefully restarted for the changes to take effect, whereas .htaccess changes occur immediately.
Creating the .htpasswd file
The password file doesn't necessarily need to be named .htpasswd but it is the convention. It contains a username and hashed password on each line of the file.
To create a new .htpasswd file from the command line with the user "chris" in it, do this where the -c flag tells the htpasswd to create a new file. Note that if the file already exists and you pass the -c flag then the original file will be overwritten with the new file.
htpasswd -c .htpasswd chris
To update a user's password in an existing file, or to create a new user in an existing file, simply omit the -c flag like so:
htpasswd .htpasswd chris
Remove password protection from a subdirectory or file
When a directory is password protected, all subdirectories and files are also password protected. It is possible to remove the password protection on a subdirectory or even just an individual file. I will show how to do this in tomorrow's post.