Let’s say you need to protect few directories (/def, /ghi, /mno) from following tree. Then please follow the further mention steps
- /var/www/html
- /abc
- /def
- /ghi
- /jkl
- /mno
- Create the .htpasswd file in /var/www directory from below command
root@amitanvir:~# cd /var/www/ root@amitanvir:/var/www# htpasswd -c .htpasswd username1
The console will prompt to enter (and re-enter) a password for username1.
- Set permission for the .htpasswd file
root@amitanvir:/var/www# chmod 644 .htpasswd
- Create a file called .htaccess within the directory (/var/www/html/def) you want to password protect.
root@amitanvir:/var/www/html/def# nano .htaccess
- Paste the following in .htaccess file
AuthUserFile /var/www/.htpasswd AuthGroupFile /dev/null AuthName "Secure Directory" AuthType Basic require user username1 require user username2
- Save it & restart Apache Service. The folder is now password protected when we access it via web browser.
- Copy this .htaccess file in other directories & restart the Apache service.
Note:
- The -c option in htpasswd -c .htpasswd username1 will create a new file and save the encrypted password. If the file already exists then it’ll be cleared completely, and re-created with the last username and encrypted password
- Please use the below command if you are facing Internal Server Error with log entry containing Invalid command ‘AuthGroupFile’, perhaps misspelled or defined by a module not included in the server configuration
a2enmod authz_groupfile