Password Protecting Files/Directories on Apache2 with .htpasswd and .htaccess

Note: You must have sudo/root access for some commands. The htpasswd file is where you set the specific username and password. To generate this file run the following command: htpasswd -c /path/to/directory/.htpasswd <username> (Replace /path/to/directory/ and username with your web site's path and desired username.)

It will then ask for your desired password. The resulting file will be encrypted. If you want to add additional users, run the command again without the -c flag as shown below:

htpasswd -c /path/to/directory/.htpasswd <username> You will want to make sure to place the .htaccess file in the directory you want password protected.

Copy and paste the following code into the .htaccess file:

For directory:
AuthName "Dialog prompt" AuthType Basic AuthUserFile /path/to/directory/.htpasswd Require valid-user
For file
<Files file.ext> AuthName "Dialog prompt" AuthType Basic AuthUserFile /path/to/directory/.htpasswd Require valid-user </Files>
This is not intended to provide a perfect or fool-proof secure way to protect a directory. Any attackers who can get the password will be able to access the directory's contents as well, especially since this method is only single-factor. Do NOT use this to hide your critical information on a publicly available web server. I hereby disclaim all liability from using this as a security measure.
Anton McClure / anton@aperture.nonpaged.com