How to protect and restrict access to a web directory using Apache web server

If you want to use the method described bellow, your Apache web server should have mod_auth and mod_access enabled.

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:


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 ). 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 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 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


No comments yet

Back to articles list

This page was last modified on 2024-07-19 11:15:27