1. Edit your Apache configuration file (httpd.conf or apache2.conf) and make sure that you have ‘AllowOverride AuthConfig’ directive within the ‘DocumentRoot’ directory entry.
Save the configuration file and restart Apache.
RPM based distros:
# /etc/init.d/httpd restart
Debian based distros:
# /etc/init.d/apache2 restart
2. Create a password file without using a text editor. Use the ‘htpasswd’ command instead. ‘htpasswd’ is used to create and update the flat-files used to store usernames and password for basic authentication of Apache users. It’s recommended to create the password file somewhere outside the Apache document root, so visitors will not be able to download it.
Create the password file by executing:
# htpasswd -c /path/to/password-file
Make sure that the newly created password file is readable by Apache. If not, setup the correct permissions using the ‘chown’ command. Use the following command to find the Apache’s username:
# grep -ie "^user" /etc/httpd/conf/httpd.conf
or
# grep -ie "^user" /etc/apache2/apache2.conf
Then change the owner of the file:
# chown user:group /path/to/password-file
Where ‘user’ is the output of the ‘grep’ command.
3. Create the .htaccess file using some text editor (mcedit, vi, nano…) in the directory that you want password protected, and add the following text:
AuthType Basic AuthName AuthUserFile /path/to/password-file Require user
4. After everything is done, you can test the configuration by opening the password protected directory with your web browser. In our case we created the .htaccess file in ‘/var/www/html/protected/’ directory, so we tried opening http://domain.com/protected which will now prompt you for a username and password before showing you the contents.
PS. If you liked this post please share it with your friends on the social networks using the buttons on the left or simply leave a reply below. Thanks.