Apache - Requiring Auth With .htpasswd And .htaccess

If you need to restrict access to a folder that the Apache Webserver is serving, you can make use of the .htaccess and .htpasswd files. Although .htaccess can define the password file, use these names since the default Apache configuration doesn't export these files, which is something you need for security.

To create .htpasswd file with an encrypted password, use the htpasswd command in a shell:

htpasswd .htpasswd username

The contents of .htaccess can be something like:

AuthUserFile /path/to/dir/.htpasswd
AuthName "Members Only"
AuthType Basic
Require valid-user

The AuthUserFile path must be absolute, relative path doesn't work.