This article explains how to restrict access to directories with Basic HTTP Authentication. Basic HTTP Authentication (or Basic Access Authentication) is a simple security mechanism to restrict access to websites or some parts of them by requiring an username and password, which is managed by a visitor's web browser when making a request.
Generate the password file
At first, you need to create your password file, which will be placed on your server. It can be done by one of two methods:
- Using our online .htpasswd generator tool (the easier way).
- Using htpasswd utility (the standard way).
Using our online .htpasswd generator
Generating .htpasswd files with our password tool is easy, just enter desired username and password and get the resulting file.
Using htpasswd utility
htpasswd utility is bundled with Apache and allows to create and update the flat-files used to store usernames and password for basic authentication of HTTP users.
htpasswd encrypts passwords using either a version of MD5 modified for Apache, or the system's crypt() routine. Files managed by htpasswd may contain both types of passwords; some user records may have MD5-encrypted passwords while others in the same file may have passwords encrypted with crypt().
Basically, to create password file you need to execute htpasswd with several arguments:
htpasswd -cb passwdfilename username password
where [-c] switch means "create the passwdfile" and [-b] means "get the password from the command line rather than prompting for it". For list of all htpasswd switches invoke htpasswd -h
Upload your .htpasswd
Now you need to upload password file that you've generated to your web server. For security, you should not upload the .htpasswd file to a directory that is web accessible. Password file should be placed above your www root/htdocs directory. After uploading is complete, you need to find out the full path to this file. Please note that this is not an URL, and this is not a FTP server path, this is a full filepath (on the unix systems it will be something like /home/user/path/.htaccess).
<?php echo getcwd(); ?>
Create .htaccess directives
Create an .htaccess file in the directory you wish to password protect (if you don't have one yet). If you place this file in your web root directory, it will password protect your entire web site.
The authorization directives may look like this:
AuthName "Restricted area" AuthUserFile /home/loginname/.htpasswd AuthType Basic require valid-user
You should enter path to your .htpasswd file in AuthUserFile line. You can also supply another AuthName (it will be used in a prompt).
Now you can test your password protection. Password will be required for access to the folder you specified and all underlying files and folders.