First make sure your Apache configuration is set for allowing .htaccess. Read this Article first before you move to the next steps.
.htaccess File Creation:
Let's assume /test-dir1 is to be password protected.
$ cd /var/www/html/test-dir1
$ vi .htaccess
Write the following lines into this file:
AuthName "Authorized Users Only."
require user testusr
Telling Apache About Users:
Now we have to inform Apache about the user and its password.
$ htpasswd -c /etc/httpd/conf/.htpasswd testusr
The above command will work if you have htpasswd in your /usr/local/bin and it happens if you install Apache from RPM. /etc/httpd/conf/.htpasswd is the location of file that will contain the authenticated/trusted user password.
$ cd /apache/bin/
$ ./htpasswd -c /etc/httpd/conf/.htpasswd testusr
The above commands correct if you have installed Apache from the sources, $ cd /apache/bin can be adjusted according to your system, as maybe you have installed it somewhere else.
.htpasswd File Permission:
We need to set the file permission of the .htpasswd file and make the apache user the owner of this file.
$ chown apache.apache /etc/httpd/conf/.htpasswd
Notes on Apache htaccess disabled on Debain/Ubuntu server:
Iv jumped back to using my home media server as a web server for testing, and realized that apache2 wouldn’t recognize .htacess files, after some googling i found the answer, you need to open a terminal or putty session:
and open “default” up in your editor or choice
sudo nano default
Default for AllowOverride is none, it should be All, so your overall “default” file should look like this;
Options Indexes FollowSymLinks MultiViews
allow from all
# This directive allows us to have apache2's default start page
# in /apache2-default/, but still have / go to the right place
# Commented out for Ubuntu
#RedirectMatch ^/$ /apache2-default/
Then all you need to do is restart apache2:
sudo /etc/init.d/apache2 restart