How to password protect folder/files using htaccess file?

Use the following htaccess code to enable authentication for certain files and folders from being accessed. The code has examples of password protection for a single file and password protection for a entire directory using htaccess file.

# to protect a file

AuthType Basic
AuthName “Prompt”
AuthUserFile /home/path/.htpasswd
Require valid-user

# password-protect a directory

AuthType basic
AuthName “This directory is protected”
AuthUserFile /home/path/.htpasswd
AuthGroupFile /dev/null
Require valid-user