.htpasswd

Article by on April 11, 2012, last modified on May 15, 2012

Generating the File

First, you must generate the htpasswd file using the htpasswd tool:

htpasswd -c .htpasswd user1
htpasswd .htpasswd user2
htpasswd .htpasswd user3

Notice that the '-c' flag creates the file, but only for the first user. If you use the flag again it will erase whatever users had their passwords added to the file previously.

There is a neat utility for generating htpasswd passwords: http://www.htaccesstools.com/htpasswd-generator/. However, I do not know who owns the site so I personally would not recommend using it for passwords of any degree of importance.

Editing .htaccess

Next, you need to edit the .htaccess file in the directory you want to lock down (or add it to your virtual hosts directives if you have htaccess turned off). A typical htaccess looks like:

AuthUserFile .htpasswd
AuthName "User Login"
AuthType Basic
require valid-user

Moving .htpassword Outside of the Web Root

As a security measure, it is good to put the .htpasswd file outside of the web root folder. For example, say your web root is '/var/www/mysite.com/html', you could place your .htpasswd file in '/var/www/mysite.com/.htpasswd' and your .htaccess file in '/var/www/mysite.com/html'. Then, your .htaccess file would look something like:

AuthUserFile "/var/www/mysite.com/.htpasswd"
AuthName "User Login"
AuthType Basic
require valid-user

References:

http://www.htaccesstools.com/
http://www.htaccesstools.com/articles/htpasswd/
http://www.htaccesstools.com/articles/create-password-for-htpasswd-file-using-php/
http://www.sitedeveloper.ws/tutorials/htaccess.htm

Older Articles »