The easiest way to protect a web directory is to use a .htaccess file. A .htaccess file is a directory level configuration file used by several web servers including the highly popular Apache. The .htaccess file is placed in a web directory and the commands in the file controls the behavior of that directory.
A .htaccess file is used mainly for 3 purposes: authentication, the re-writing of URLs and cache control. Today, I’ll show you how to password protect a web directory using the .htaccess file.
First, create a .htpasswd file. For security purposes, place the .htpasswd file outside of your web directory. You can place it anywhere in your file system, but your home directory is probably the best place for it. To create a .htaccess file, issue this command in your Terminal:
# sudo htpasswd -bc /home/ulysses/.htpasswd username password
The htpasswd command will create a file called .htpasswd in your home directory. The period at the beginning of the file denotes that it is a hidden file. You can view it by issuing a “ls -a” command from your Terminal. Don’t forget to supply your own username and password.
Next, make a .htaccess file in the web directory that you want protected. In this example, we will password protect a web directory located in /var/www/widget.
# cd /var/www/widget # vi .htaccess
Type in the following code in the .htaccess file.
AuthUserFile /home/ulysses/.htpasswd AuthName EnterPassword AuthType Basic <Limit GET POST> require valid-user </Limit>
Save the file and open your browser and check if the web directory is password protected. You should see something similar to this from your browser.