How to secure Apache web server in Linux using password (.htaccess)

Here I have provided simple steps to configure your webpage with login authentication. So that you can prevent unauthorized access to your pages on the website.

I have used Red Hat 6 machine for these commands so kindly check the same if planning to user other distribution of Linux.

These are the required attributes which has to be placed and used properly inside the main apache configuration file.

This option will disable the access to read .htaccess file
AllowOverride None
This option with enable the access to read .htaccess file
AllowOverride AuthConfig
This will signify the authentication file for required user

AuthUserfile /location/of/file
AuthGroupFile /location/of/group
This will give an output name which you want to be visible on the login prompt screen

AuthName "Restricted Area"
NOTE: Create a new .htaccess file inside the directory where you want the authentication. In our case it is inside /var/www.

Create a authentication file inside the directory you want to protect.
# htpasswd  /var/www/.htaccess  username

# htpasswd  /var/www/.htaccess  deepak
New password:
Re-type new password:
Adding password for user deepak
Give appropriate permission to prevent anauthorized access
# chmod 700 /var/www/.htaccess
Add these lines at the end of the config file for apache

# vi /etc/httpd/conf/httpd.conf
<Directory /var/www/html>
AllowOverride AuthConfig
Order allow,deny
AuthType Basic
AuthName "Login Message on the prompt screen"
AuthUserFile /var/www/.htaccess
Require user deepak
Allow from all
</Directory>

Restart the services

# service httpd restart
Now try to access your page on the browser, you will be prompted for login authentication

http://192.168.0.138