Web : How to password protect a Web directory with htaccess

By | October 1, 2019

If for any particular reason you need to password protect a Web directory, on an Apache Web server using htaccess, here are steps below :

1. If not already existing, create a file name “.htaccess” at the root of the folder you want to protect :

touch .htaccess

2. Make sure it is readable by the Web server user (write access can also be granted for convenience, but may represent a security risk) :

chown user:group .htaccess
chmod 440 .htaccess

3. Add or append the following into the “.htaccess” file (edit AuthUserFile accordingly) :

AuthUserFile /path/to/user/root-folder/.htpasswd
AuthGroupFile /dev/null
AuthName "Secure Document"
AuthType Basic
require user username

Note : You need to replace “username” by the actual username you want. You may also append as many users as you need.

4. Create the password file (we recommend putting this file outside of your Document Root (within your home folder but inaccessible by Web visitors for enhanced security) :

touch /path/to/user/root-folder/.htpasswd

5. Create the user/password :

htpasswd -c /path/to/user/root-folder/.htpasswd username

Note : You may repeat the step above for as many users you need and initially entered in the .htaccess file above. If you do not have shell access, there are many generators available on the Web, you may just copy/paste the content to a text file and upload it with