Simple-to-configure and -use access control is a very versatile feature of the Apache webserver. This article summarizes the basic steps for securing your website with such a login facility. Access control is enabled in the .htaccess file contained in the topmost folder to which it shall be applied (typically the root of your site). All directory levels below this will inherit the settings from this file (as explained here). Add the following lines to your .htaccess file:

# absolute or relative
AuthUserFile <path-to-document-root>/.htpasswd
AuthName "This message appears in the login dialog"
AuthType Basic # not very safe, but OK for temporary access control
Require valid-user # requires a user that is listed in the .htpasswd file
DirectoryIndex index.html #only necessary to show the test site

In order to test your access control settings, create an index.html in your site’s root directory:

<html><body><h1>You are allowed to see this :-)</h1></body></html>

In the same directory, create an .htpasswd file with initial user horst:

htpasswd -c .htpasswd horst
 # Afterwards, type and re-type horst's password

You may add more users as follows:

htpasswd .htpasswd bianca
htpasswd .htpasswd bernhar

Each line of .htpasswd contains a user name, followed by his/her MD5-encrypted password. If you see the passwords in plain text, delete .htpasswd and re-issue all of the above commands with option -m.

A number of online tools for generating .htpasswd and the directives in .htaccess exit, such as that on dynamicdrive.com.

Links

  • [1] htaccess documentation
  • [2] Online htaccess and htpasswd generator (one in a “million”)