Password Protect a Directory in Apache with htpasswd

By | 2013/04/03

Here is a quick and easy way to password protect a directory in Apache. I use this similar setup to password protect my ownCloud instance!

Step 1: Create a user, and set the password. This example creates a username admin as an illustration. Tack s uses a stronger SHA encryption for passwords vs the default MD5.

Note: the location of the htpasswd file can exist anywhere, but I like to keep it as a dot file in the /etc/apache2/ (or /etc/httpd/ for CentOS peeps) directory.

$ sudo htpasswd -s -c /etc/apache2/.htpasswd admin
New password: 
Re-type new password: 
Adding password for user admin

Step 2: Next create a file called .htaccess in the directory you wish to protect with the contents below. Or if an .htaccess file already exists, add the following lines:

AuthUserFile /etc/apache2/.htpasswd
AuthType Basic
AuthName "hello"
Require valid-user

Now when trying to access that directory, you will be prompted with a browser login as a layer of protection: