.htaccess Passwords

By far one of the most useful features of htaccess is the fact that it can password protect directories. Although there are many other ways to do it, like PHP, not many offer the same amount of security as htaccess.

Using passwords with .htacces requires an extra file, and that is .htpasswd.

The .htpasswd file contains a list of the valid usernames and passwords for the file or directory you are protecting.

It is formatted like so:

username:password
username:password
username:password

etc.

Easy huh? Not quite so easy. You can type the username exactly as you want it, but the password has to be encrypted. Fortunately there are many sites that will encrypt the passwords for you.
Of course, google knows all, it includes results to sites:
Like this one,
and this one,
also, this one.

So you htpasswd file should now look vaguely like this:
yacoby:Yj4yBHCBiPpK6

Upload the .htpasswd file to your webhost. It is advisable that you upload to a place that cannot be viewed. Above your public_html directory is a good idea.

Now we need to write the .htaccess file. A basic .htaccess file dealing with password protection should look something like this:

AuthUserFile /root/usr/pathto/.htpasswd
AuthType Basic
AuthName "Private Directory"
Require valid-user

AuthUserFile /root/usr/path/to/.htpasswd
This is the full path (the server path, not the URL) to your .htpasswd file. If you have it below the public_html directory, make sure it cannot be viewed.

AuthType Basic
We use this because we use "basic" HTTP authentication

AuthName "Private Directory"
This is the name that appears on the the dialog box that opens to display the password. It appears in various places depending on the browser used.

Require valid-user
This tells the server to validate the password. If you only wanted a particular user in your .htpasswd file to be able to access this part of the site, you would use:
require user username-here