When surfing the web, you may have come across web pages that prompt you to provide a username and password with a dialog box like the one below:
Implementing this kind of password protection is actually fairly easy and requires only a few steps:
- Create a text file (usually named “.htpasswd”) which stores the allowed usernames and passwords.
- Insert a few lines of code to an “.htaccess” file (which I introduced in my last article).
.htpasswd File
A typical “.htpasswd” file looks like this:
john:hjEnaBHSVih/2 jane:nwFprWeMvftDc
Each line in the file contains a username and an encrypted password separated by a colon. To create your own password entries, you can use this simple .htpasswd generator.
The .htpasswd file should be uploaded to a directory that is not accessible to web surfers (such as the protected directory or the directory above your www root folder). When uploading the file, be sure to use ASCII mode (rather than binary mode).
.htaccess File
The .htaccess file should contain the following code:
AuthName "Restricted Directory" AuthType Basic AuthUserFile /user/home/www/directory/.htpasswd AuthGroupFile /dev/null require valid-user
Make sure that the path specified in the “AuthUserFile” directive points to the .htpasswd file on your web server. Upload the edited file into the directory you want to protect.
