How to protect web directories using .htaccess

To protect web directories with password using .htaccess File

This article helps you to protect other search engines from accessing information of site when it’ s in the development phase.

To set password for Directories

---------------- On RedHat/CentOS based systems ----------------
vi /etc/httpd/conf/httpd.conf

---------------- On Debian/Ubuntu based systems ----------------
nano /etc/apache2/sites-available/000-default.conf

To find root of Apache Document directory

On Apache 2.2 Version

Options Indexes Includes FollowSymLinks MultiViews

AllowOverride All
allow,deny
Allow from all


On Apache 2.4 Version

Options Indexes Includes FollowSymLinks MultiViews
AllowOverride All
Require all granted

To save file and restart

--------------- On Systemd -------------------

systemctl restart httpd [On RedHat based systems]
systemctl restart apache2 [On Debian based systems]

--------------- On SysV init -----------------
service httpd restart [On RedHat based systems]
service apache2 restart [On Debian based systems]

To generate user name and password

Syntax
htpasswd -c filename username

-c option helps to keep encrypted username and password

To create a new directory

mkdir /home/linuxhelp

To generate username and password
htpasswd -c /home/linuxhelp/test-file linuxhelp

To change ownership of file

---------- On RedHat/CentOS based systems ----------------

chown apache: /home/linuxhelp/test-file
chmod 640 /home/linuxhelp/test-file

----------- On Debian/Ubuntu based systems ----------------
chown www-data /home/linuxhelp/test-file
chmod 640 /home/linuxhelp/test-file

To request password to access targeted directory

vi /var/www/html/.htaccess
AuthType Basic
AuthName " Restricted Access" 
AuthUserFile /home/linuxhelp/test-file
Require user linuxhelp

To save file and setup

http://ip-address

Tag : Htaccess
FAQ
Q
May i know What are the types of authentication can be used for apache web server?
A
There are two types of authentication which are Basic and digest authentication. These two can be user for apache webserver
Q
What are the difference between basic and digest authentication?
A
The differences are basic & digest authentication are
Basic authentication uses base64 encoding which is less secure, whereas the digest authentication uses hash algorithm which is more secure.
Q
What is the ownership name for apache webserver directory on ubuntu ?
A
The apache web directory uses "ww-data" for both user & group at ubuntu/debian
Q
What are all the files does htpasswd contains ?
A
The htaccess file should contain the following:

AuthType Basic
AuthName "Password Protected Area"
AuthUserFile /path/to/.htpasswd
Require valid-user
Q
Where to find apache default configuration file on ubuntu?
A
You can find the default configuration under /etc/apache2/sites-available/000-default.conf