The most common usages of .htaccess is to restrict access to all of the files within a directory. You do this by setting up a simple text file as shown below.

AuthUserFile /usr3/home/tommy/Webmaster/htaccess/.htpasswd
AuthName "Access"
AuthType Basic
<limit GET>
require user htaccessdemo
</limit>

Note: .htaccess will not work if there are extra spaces after AuthUserFile.

There is a slight hitch to this, however, making this process more complex than it appears. If you look at the example above, you should notice that the password is not included. If you think for a minute longer you should realize that if you include the password then it will be visible to anyone who happens to see the file.

This problem is solved with a second file called .htpasswd, which contains encrypted passwords. The .htpasswd file for the example above is shown below.

htaccessdemo:tn6q6ZMFM1QWc

As you can see, the password (the strange text following the “htaccessdemo:”) is encrypted. This means you cannot simply view the password with a text editor – you have to know what it is.

Okay, how do you get passwords in the password file? You must telnet to the server and issue the command shown below:

htpasswd -c .htpasswd someuser

Include the -c option to create the password file. If not included, the password will be appended.

Note: If you search through the various CGI collections on the web, you will several Perl scripts to perform this encryption for you. These scripts are especially useful if you do not have telnet access to the server. Just be sure these scripts are thoroughly protected (or better yet, copy them to your server when you need them and delete them when finished).

It is important to understand that there is no correspondence of any kind with Unix accounts. The usernames in .htaccess and .htpasswd files are not Unix accounts. (This is different than Windows NT servers).

As a note, this is the only way to ensure proper security on a Unix server. There are many other ways to “protect” a page (such as Bravenet), but they are in no way as secure as the .htpasswd file.