Password protection with Apache and .htaccessPassword protection with Apache and .htaccess

Posted June 22nd, 2009 in Apache

It's easy to password protect a directory with Apache and .htaccess files but I'm always forgetting the syntax so have put this post up so I don't have to search the Internet every time I need to look it up...

.htacess file

In your .htaccess file put the following:

AuthUserFile /full/path/to/.htpasswd
AuthType Basic
AuthName "Restricted Access"
Require user myusername

/full/path/to/.htpasswd needs to be the full path and filename for the file which contains the passwords. It cannot be a relative path otherwise you'll get an internal server error message.

Change the text between the quotes after AuthName to whatever it is you want the authorization dialog to tell the user.

Change "myusername" to the name of the person who can log in, where the name is an entry in the .htpasswd file. You can have multiple user names here, separated by a space.

.htpasswd file

The .htpasswd file contains the login names and hashed passwords.

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

Related posts: