Basically, you only need to place the following two files in the corresponding directory you want to password protect with.

.htaccess

.htpasswd

For example, if you want to protect a folder in your home directory called wordpress, you just need to place these two files under that directory. If you use a remote webserver, you may need to create these two files locally on your machine and upload them.

To create the files on windows, since both file don’t have a file name, but only have extensions (.XXX), you might not be able to change an existing file to this filename. To get around with this problem, you can use notepad, and do the following when save the file. Make sure in the “save as type” dropdown list, choose “All Files (*.*)”.

image 

That is what the contents of the .htpasswd file should look like. One username and password per line, separated by a colon.

test:$apr1$fNOlGFNA$vegBiyiW.zQZ9WMCtAMKp1

Notice the password is encrypted though. You will need to use a special tool to encrypt your password in this way (MD5). David Walsh has a tool just for this. (Note: I don’t trust this tool since it records your username and password.)

If you have Apache installed, you can simply use the htpasswd.exe file under the apache/bin directory to generate the password. If Win7 does not allow you to write to a particular directory, you can try the following.

htpasswd.exe -nb test test >> c:\Temp\.htpasswd to generate the password in the temp directory first, and copy it to the directory you want to use.

 

Here is what I have put in my .htaccess file, and .htaccess file is placed under the wordpress directory.

AuthType Basic

AuthName "restricted area"

AuthUserFile C:\xampp\htdocs\wordpress\.htpasswd

require valid-user

Note the above directory is the web directory I have on my windows machine. If you use Linux, the directory may look like: /home/21410/domains/css-tricks.com/html/examples/PasswordProtected/.htpasswd

 

And here is what I have put in my .htpasswd file

test:$apr1$fNOlGFNA$vegBiyiW.zQZ9WMCtAMKp1

 

Note: this kind of password protection does not work on the localhost, so don’t waste your time testing it. 

Here is a screen shot on how it works:

clip_image001

 

This post is modified from http://css-tricks.com/825-easily-password-protect-a-website-or-subdirectory/

Written by Shengdong Zhao

Shen is an Associate Professor in the Computer Science Department, National University of Singapore (NUS). He is the founding director of the NUS-HCI Lab, specializing in research and innovation in the area of human computer interaction.