Saturday, June 12, 2010

Apache:create password protected directory

In this short tutorial I'll show how to restrict certain folders of your web server for certain users/groups.

Let's say we need to restrict some files that will be located under /var/www/secret (/var/www is our DocumentRoot - aka the place where our site html/java/php stuff is located).

First we need to create (-c flag) a new user and set it a password, pay attention to the file path, it will contain the username and it's encrypted password (somewhat similar to /etc/shadow):

#htpasswd -c /etc/apache2/userslist admin
New password:*****
Retype new password:*****
Adding password for user admin

We can change the password later with htpasswd command (without any flag).

After we've added the user we need to edit our site configuration file, on Debian it's located under: /etc/apache2/sites-available/default

We need to edit our directory block with the proper settings, it should look something like this (pay attention to the last directory block):

If we want to allow more than one user we can add more valid users in the "Require user" line, More elegant approach will be to create group file (like /etc/apache2/groupfile) that will look something like this:

#cat /etc/apache2/groupfile

admins:paul admin bob dave

2 lines will be changed: 
instead of require user , require group.
instead of AuthUserFile /path/to/file, AuthGroupFile /path/to/file

Last thing left is to restart apache:

#apache2ctl restart

No comments: