Sunday, January 10, 2010

How To Protect Web Page Directories With Passwords

How To Protect Web Page Directories With Passwords

You can password protect content in both the main and subdirectories of your DocumentRoot fairly easily. I know people who allow normal access to their regular Web pages, but require passwords for directories or pages that show MRTG or Webalizer data. This example shows how to password protect the /home/www directory.

1) Use Apache's htpasswd password utility to create username/password combinations independent of your system login password for Web page access. You have to specify the location of the password file, and if it doesn't yet exist, you have to include a -c, or create, switch on the command line. I recommend placing the file in your /etc/httpd/conf directory, away from the DocumentRoot tree where Web users could possibly view it. Here is an example for a first user named peter and a second named paul:

[root@bigboy tmp]# htpasswd -c /etc/httpd/conf/.htpasswd peter
New password:
Re-type new password:
Adding password for user peter
[root@bigboy tmp]#

[root@bigboy tmp]# htpasswd /etc/httpd/conf/.htpasswd paul
New password:
Re-type new password:
Adding password for user paul
[root@bigboy tmp]#

2) Make the .htpasswd file readable by all users.

[root@bigboy tmp]# chmod 644 /etc/httpd/conf/.htpasswd

3) Create a .htaccess file in the directory to which you want password control with these entries.

AuthUserFile /etc/httpd/conf/.htpasswd
AuthGroupFile /dev/null
AuthName EnterPassword
AuthType Basic
require user peter

Remember this password protects the directory and all its subdirectories. The AuthUserFile tells Apache to use the .htpasswd file. The require user statement tells Apache that only user peter in the .htpasswd file should have access. If you want all .htpasswd users to have access, replace this line with require valid-user. AuthType Basic instructs Apache to accept basic unencrypted passwords from the remote users' Web browser.

4) Set the correct file protections on your new .htaccess file in the directory /home/www.

[root@bigboy tmp]# chmod 644 /home/www/.htaccess

5) Make sure your /etc/httpd/conf/http.conf file has an AllowOverride statement in a directive for any directory in the tree above /home/www. In this example below, all directories below /var/www/ require password authorization.


AllowOverride AuthConfig


6) Make sure that you have a directive that defines access to /home/www or another directory higher up in the tree.


ServerName 97.158.253.26
DocumentRoot /home/www


7) Restart Apache.

Try accessing the web site and you'll be prompted for a password.