What do .htaccess and htpasswd do for Apache Basic Authentication, and what must be true for a deployed .htaccess to take effect?
.htaccess in the web root tells Apache to require a login (AuthType Basic, Require valid-user) and where the password file is (AuthUserFile). htpasswd stores the user names and password hashes. Apache only reads .htaccess if AllowOverride permits it for that directory, and its worker user must be able to read the password file.
* Two checks decide whether the login really protects the site. *
AuthType Basic
AuthName "Protected area - please enter a password"
Require valid-user
AuthUserFile /etc/httpd/secrets/htpasswd
guest:$2y$05$MQ7RdCCRrKmBEDD/u4pks.9qAV8RCKy4YCP2pzgmc4lppfli41zC
The hash prefix $2y$ means bcrypt (made with htpasswd -B), and 05 is its cost factor. The file is kept outside the web root so it can never be downloaded.
Two conditions are easy to get wrong when automating this:
AllowOverride. On Debian,/var/www/defaults toAllowOverride None, so Apache ignores.htaccessentirely and the site stays open. The virtual host or directory config must allow at leastAllowOverride AuthConfig. (Putting theAuth*lines straight into the<Directory>block avoids.htaccessaltogether.)- Readability. Apache's workers run as an unprivileged user (
www-dataon Debian,apacheon RHEL). If the secrets directory isroot:root 0500andhtpasswdisroot:root 0400, the workers can't read them, and every login fails with a server error. Give the files to the web server's group, or make them group-readable for it.
So a check like "the URL returns HTTP 200 with the right credentials" only proves the auth works if a request without credentials gets a 401.
Go deeper:
Authentication and Authorization (Apache docs) — Basic auth,
AuthUserFile,Require..htaccess files and AllowOverride (Apache docs) — when
.htaccessis read at all.htpasswd (Apache docs) — hash formats, including bcrypt.
Basic access authentication (Wikipedia) — the 401 challenge and the Authorization header on the wire.