Enabling security using .htaccess file

lock

When working with web servers, and displaying contents, you may wish to restrict access to certain pages to only authenticated users. Which means one will require a password to view these restricted pages. Though there are several techniques to achieve this objective, the use of .htaccess is one of the most simplest, but powerful mechanism available. This goes well with Apache web servers. The dot that starts the file name will keep the file hidden within the folder

 

The Apache web server controls its security via the “httpd.conf” file. If the installation of the server is a default installation using the default configuration, without re-configuring the security control parameters using .htaccess method to restrict access to web pages is simple. Listed below are the procedures to configure it in a host named host.sample.com, where the DocumentRoot folder is /var/www/html and our restricted page is stored in /var/www/html/test/r_page.html

#] cd /var/www/html/test

#] vi .htacess

Now add the following lines

  • AuthUserFile /var/www/html/test/.htpasswd
    AuthName “Please Enter Your Password”
    AuthType Basic
    Require valid-user

 

Open the httpd main configuration file /etc/httpd/conf/httpd.conf, or the one you have in your host, and check if there are any line or block containing the folder /var/www/html/test. If there is one, make sure the line “AllowOverride does not have value None. If it is present, change it to All.

If a block with the folder name /var/www/html/test does not exist, create one as bellow at the end of the httpd.conf file.

  •  <Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order allow,deny
    allow from all
    </Directory>

Restart http server using the command “service httpd restart

 

Now let us create the password:

#] cd /var/www/html/test

#] htpasswd -c .htpasswd admin

When prompted enter the password

 

To verify the setting try accessing the web site : http://<hostname>/test

You should the prompted to enter the username and password. Use the username admin and the password you entered above.