On a modern website, you can often use your content management system to password protect a particular page. In some cases, however, you may want to protect a directory that holds general documents, pictures, videos, or other files. Furthermore, using Apache’s password protection can add an additional layer to your website’s security beyond the web application itself.
With Apache HTTP Server, you can password protect a directory using htaccess and htpasswd. An htaccess file is a hidden file, with a period in front of its name, that can apply Apache directives on a local level. Therefore, you can create a plain text .htaccess file and put it in any directory.
Follow these simple steps to password protect a directory.
1. Make a plain text file to hold your password information
You should encrypt the password to make sure that even if someone gets access to the file, they cannot read the password. You can use this web form to generate your encrypted password. For example, with the name “Bob” and the password “leftright45”, the output would be:
Paste that output into your new text file and save the file as .htpasswd. It is best to place the file outside of your web root (i.e. above public_html or htdocs).
If you have SSH access to your server, you can use a simple command to generate the password file:
htpasswd -c .htpasswd bob
2. Make another plain text file and call it “.htaccess”
Your .htaccess file will contain information about the directory as well as a path back to your .htpasswd file. It should look something like this:
AuthName "Bob’s Secure Folder"
When you are finished, place the .htaccess file in the directory or folder you wish you protect.