Sunday, July 4, 2010

Password Protect a Directory with .htaccess

Create a .htaccess file in the directory that you want to protect and add this lines below:

AuthUserFile /home/riariver/.htpasswd
AuthName "RiaRiver's Login Area"
AuthType Basic


First, you've defined the location of the .htpasswd file. This is the file that contains all the usernames and encrypted passwords for your site.

The AuthName parameter defines the title of the password entry box when the user logs in. It's not exactly the most important part of the file, but should be defined.
AuthType tells the server what sort of processing is in use, and "Basic" is the most common and perfectly adequate for almost any purpose.

If we want to grant access to everyone in the .htpasswd file, we can add this line ("valid-user" is like a keyword, telling apache any user will do):

require valid-user

If we want to just grant access to a single user, we can use "user" and their username instead of "valid-user":

require user riariver

A normal and complete .htaccess file might look like this:

AuthUserFile /home/riariver/.htpasswd
AuthName "RiaRiver's Login Area"
AuthType Basic

require user riariver


An .htpasswd file is made up of a series of lines, one for each valid user. Each line looks like this, with a username, then colon, then encrypted password:

username:encryptedpassword

The password encryption is the same as you'll find in PHP's crypt() function. It is not reversible, so you can't find out a password from the encrypted version.

A user of "riariver" and password of "riariver" might be added with the following line:

riariver:$1$fuQTAqaj$X9geTeMjTiZaq5axEH/0v

Each time you run an encryption function like "crypt", you will almost certainly get a different result. This is down to something called "salt", which in the above case was "XO" (first two letters of encrypted password). Different salt will give different encrypted values, and if not explicitly specified will be randomly generated. Don't worry though, the server is quite capable of understanding all this - if you come up with a different value for the encrypted password and replace it, everything would still work fine, as long as the password was the same.

Once you've created your .htpasswd file, you need to upload it to a safe location on your server, and check you've set the .htaccess file to point to it correctly. Then, upload the .htaccess file to the directory you want to protect and you'll be all set. Simply visit the directory to check it is all working.

Reference: http://www.addedbytes.com/

No comments:

Post a Comment