protect and restrict access to a web directory using Apache

Posted: November 11, 2009 in apache, Web Server

In the beginning
If you have a directory in you website, which you want to keep restricted access. Easy, fast and secure solution is to use Apache authentication functionality.
Step one – passwords file.
First you’ll need a file with all users and their encrypted passwords. It looks something like this:

user1:7yefORPzkOGtw
user2:Zwes8W.81oqJ2

Usernames are up to 255 chars and cannot contain :.

You can create this file manually. For password ecryption there are many tools available ( here’s one http://www.flash.net/cgi-bin/pw.pl ). Then you can upload it through ftp.

Another way to create it is to use htpasswd tool from Apache distribution.
When you irst create this file, here’ the command line:

htpasswd -c /home/vank0/.htpasswd -c vank0

It ask twice for password and user vank0 is already added. Now let’s add a few more users:

htpasswd -c /home/vank0/.htpasswd pesho
htpasswd -c /home/vank0/.htpasswd misho
htpasswd -c /home/vank0/.htpasswd diana
htpasswd -c /home/vank0/.htpasswd petq
Step two – .htaccess file
You should create an .htaccess file in the directory you want to protect. Let’s assume that document root is /home/vank0/www/, the directory is /home/vank0/www/taino/ and the website url is vank0.example.com. Here’s the content of /home/vank0/www/taino/.htaccess

AuthType Basic
AuthName “Secret directory”
AuthUserFile /home/vank0/.htpasswd
Require valid-user

This way directory http://vank0.example.com/taino/ is accessible for each of the users in /home/vank0/.htpasswd
Just one user
If you want to make directory /home/vank0/www/po-taino/ accessible only for user vank0, you should create /home/vank0/www/po-taino/.htaccess with this content:

AuthType Basic
AuthName “Secret directory of vank0″
AuthUserFile /home/vank0/.htpasswd
Require user vank0
Some users
A directory can be accessible only for a few of the users in the password file. For example only pesho and misho should see /home/vank0/www/pesho-misho/. We need another file – containing user groups, where only one group is set. The file is /home/vank0/.htgroups, with single row:

grupata: misho pesho

Then you should create /home/vank0/www/pesho-misho/.htaccess with this content:

AuthType Basic
AuthName “Secret directory of grupata”
AuthUserFile /home/vank0/.htpasswd
AuthGroupFile /home/vank0/.htgroups
Require group grupata

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s