HTTP Basic Authentication with Apache's .htaccess files

You can avoid server-script programming, by using the Apache server's mod_auth authentication module and .htaccess files.

It is done by placing an .htaccess file in a directory, which will control accesses to files and any subdirectories in this directory.

The .htaccess file may look like
AuthUserFile /import/home/hilde/Webprogramming/.htpass

AuthName "Web Programming Secret Pages"

AuthType Basic

require valid-user

The line
AuthUserFile /import/home/hilde/Webprogramming/.htpass
specifies the text file in which the user names and passwords is recorded.

This page should NOT be in the web-tree...

The line
AuthName "Web Programming Secret Pages"
specifies the name of the access restricted area of the web-site.

The remaning lines
AuthType Basic
require valid-user
specify the authentication method (Basic) and who is allowed to pass (any authenticated user).

The file .htpass may look like
hilde:NRSDtsceWfu0I
henrik:aiM.//KZIbzGo

Note that the passwords are stored in encrypted form. You might perform the encryption yourself using the PHP function crypt
which can be tested here.

Note that the crypt function uses a salt to generate the encryption.

In the .htpass file, the salt can be recovered as the two first characters of the encrypted string. (In fact the crypt function supports several encryption types, see here which encryption types are supported. Read more in the php manual).

We do not need to write a PHP script. The password file can be automatically generated with the program htpasswd that comes with the Apache distribution.

Below is shown the steps I took to generate a password file with two users.
> htpasswd -bc .htpass  hilde WP
Adding password for user hilde
> htpasswd -b .htpass henrik pass
Adding password for user henrik
> more .htpass
hilde:NRSDtsceWfu0I
henrik:aiM.//KZIbzGo
The c option tells htpasswd to generate a new file.
The b option tells htpasswd to expect the password as a parameter.

You may test the above authentication here. Try first not to provide a valid password.

Note that