How to Password Protect a Web Directory

by jim on February 9th, 2010

The easiest way to put password protection on a directory of your website (this assumes you’re running Apache) is to take advantage of the basic authentication features of Apache. htpasswd is the command you’ll be using to create and update the files that will store your usernames and passwords.

Create the directory you want to protect and navigate into it. Next, run the “pwd” command, that will give you the full pathname of the directory. Create and edit the .htaccess file in that directory, it should have this at the top:

AuthUserFile /usr/you/hidden-directory/.htpasswd
AuthGroupFile /dev/null
AuthName "Super secret directory"
AuthType Basic
 
<Limit GET>
require valid-user
</Limit>

First line, AuthUserFile, indicates the location of your password file. You should replace /usr/you/hidden-directory/ with the information from the “pwd” command. AuthGroupFile, which we have set to dev/null, sets the list of user groups for authentication but we won’t be needing that. You will limit the users based on who has a username and password set in the htpasswd. AuthName sets the title of the username/password dialog that the users will see asking them to log in. Finally AuthType sets whether you want the password to be MD5 hashed (digest) or not (basic). For most cases, basic will work fine, but if you are concerned someone is sniffing your data, you should use digest.

If you use digest, you’ll have to follow a different set of instructions as you will be using htdigest instead of htpasswd. Remember, while the password is encrypted, any of the subsequent data you send or access will not be. You can read more about it here.

I put the .htpasswd file inside the hidden-directory so from here I just create a new user using htpasswd:

htpasswd -c .htpasswd [new_user]

You will be prompted for a password and the user will be created.

If you already have an .htpasswd file and want to append to it, use this instead (take out the -c):

htpasswd .htpasswd [new_user]

If you run into any problems (such as forgetting your login), you can always delete the .htpasswd file and recreate it.

RSS Subscribe Like this article? Get all the latest articles sent to your email for free every day. Just click "Subscribe" and enter your email. Your email will only be used for this daily subscription and you can unsubscribe anytime.

Leave a Reply