How to password protect a directory (htpasswd + htaccess)

Password protecting a directory with .htaccess and .htpasswd

There may be parts of your site that you wish to restrict or allow access by “authorized users” only. You may have a family photo album or just some private files that you only want certain people to have access to.

To add a username/password pop-up box to a specific directory, follow these steps –

1. You must have SSH access. This cannot be done via ftp. If you have not already requested SSH access, please stop and submit a request for SSH access from the helpdesk section of your control panel. You will receive a confirmation email once SSH access has been granted within 24 hours. Once SSH access has been granted, proceed to step 2.

2. Create or open the directory you wish to protect.

If the directory already exist, type cd location/of/directory/

(Example – cd www/pictures/private_pictures/)

If you need to create the directory, type mkdir location/you/wish/

(Example – mkdir -p www/pictures/private_pictures)

3. Once you are in the directory that you wish to protect, use an editor such as vi or emacs to create a file called .htaccess (lower case letters with the leading period) that looks just like this:

AuthUserFile /home/YOUR_ACCOUNT_USERNAME/.htpasswd
AuthGroupFile /dev/null
AuthName “TITLE YOU WANT TO APPEAR ON THE PASSWORD BOX”
AuthType Basic
require valid-user

4. To create the password file, issue the following command –

htpasswd -c /home/YOUR_ACCOUNT_USERNAME/.htpasswd USER_NAME

(replace USER_NAME with the username you would like visitors to enter to gain access to the protected directory)

If you later on need to update a users password, use this:

htpasswd /home/YOUR_ACCOUNT_USERNAME/.htpasswd NEW_USER_NAME

(the same command without the -c option. The -c option tells htpasswd to create a new file. If you don’t use it, it will add a new user to the file).

5. The system will ask you to enter the password for this user.

6. If you wish to add multiple users, use the same command in step 4, but without the -c

htpasswd /home/YOUR_ACCOUNT_USERNAME/.htpasswd ANOTHER_USERNAME

(The -c option in step 4 is only for the initial creation of the file)

That’s all there is to it! If you experience any unexpected problems, or you change your mind about restricting access, just issue the command ‘rm .htaccess’ to remove (or use the regular delete function in your ftp program to delete the .htaccess file).

Leave a Reply

Your email address will not be published. Required fields are marked *