Create htpasswd File to Protect Directory

Apache configuration and how to create an .htpasswd file to protect a directory with user and password

How to protect a directory using Apache .htaccess and .htpasswd files.
.htaccess : has the path to the .htpasswd file
.htpasswd : stores users and encripted passwords


Create the folder to be protected


mkdir protected
chmod g+r,g+x,o-r,o-x protected
cd protected


Change apache conf file to allow htaccess for your folder

With Options -Indexes to avoid directory listing and
AllowOverride All to enable htaccess


<Directory   "/var/my-path/protected">
    Options     -Indexes
    AllowOverride All
 </Directory>


Restart Apache

(Red Hat):

Test configuration:
/etc/init.d/httpd configtest

Then restart:
/etc/init.d/httpd restart

(Ubuntu):

sudo /etc/init.d/apache2 restart


Create the .htaccess file


AuthUserFile /var/my-path/protected/.htpasswd
AuthName "Login"
AuthType Basic
<LIMIT GET POST>
        Require valid-user
</LIMIT>


Create .htpasswd  file
The -c parameter is used to create the .htpasswd file, so you will use it at first only once

htpasswd -c .htpasswd user1
[It will ask you the password]

For the next users do not use the -c parameter
htpasswd .htpasswd user2
[It will ask you the password]


And so on for other users