Protect the web directories by user authentication in apache


Protect the web directories by user authentication in apache

Directory Password Protection 

In order to restrict the clients from accessing the web directory of a server and to allow only certain users, apache uses the Directory Password Protection Method.

How to Set Password Protection to directory ?

       In Apache the .htaccess (Name of the Distributed Configuration file) file is placed under the Directory that we need to protect.To configure this directory password protection follow the below steps.

 Step 1:

In the Apache configuration file httpd.conf, add an entry in Virtualhost container to secure the protected directories.

DocumentRoot /var/www/html
AccessFileName .htaccess
<Directory /var/www/html/private >
AllowOverride All

      In the above configuration we need to protect the /var/www/html/private web directory. The .htaccess is the distributed file name placed under the protected directory,we can change this file name as per our need by assign any name in AccessFileName directive. In the Directory container we should mention the absolute path of protected directory, Inside the Directory container the All option in AllowOverride will allow all the possible configuration directives in the .htaccess file.

Note: If AllowOverride is set to none then the apache ignored the .htaccess file

Step 2:

Now Add a valid authorized user for the protected web directory by using htpasswd command

# htpasswd -c /var/www/html/private/.htpasswd <username>

The htpasswd command is used to generate the username and password for user authentication in protected directory.The option -c is used to create the password file (.htpasswd) if it does not exist.

Step 3:

 Now configure the in .htaccess file which is placed under the protected directory “/var/www/html/private/.htaccess” as below.

AuthType Basic
AuthName “Private User Access”
AuthUserFile /var/www/html/private/.htpasswd
Require valid-user
Order Allow,Deny
Allow from all

   In this above configuration entered in .htaccess file,the AuthType is configured as Basic,which defines the type of user authentication for the directory.The AuthName defines name of the authorization realm for a directory.The authenticated user password file stored location is denoted by AuthUserFile directive.The Require directive defines the permitted user to access the protected directory.we can also deny or allow from which client IP should access the protected IP by Allow and Deny Directive.

Note: make the .htaccess and .htpasswd file hidden from clients for security purpose.

Output :

All the configurations are over.Now just restart the apache service and call the configured virtual host protected web directory by browser.

 Now give the authorized user name and password and press enter

 Now you accessed the protected web directory



Leave a Reply

Your email address will not be published. Required fields are marked *