Thursday, December 13. 2007

Restricting access to directories and files in Apache's httpd

I always have to look it up how to restrict access to some files or directories on my web server, so I write it down here. Two steps:

  1. You need a password file
  2. You must specify the restrictions

Creating a password file

That's pretty easy. You create a new password file with

touch /path/to/password-file.txt

Make sure the webserver can access the /path/to/password-file.txt. This means the webserver has list permissions (x) for the directories /, /path, and /path/to and read permissions (r) for the actual file. Don't put the password file into your web space because everybody can see the encrypted passwords and crack them at home.

You add new users to the password file with

htpasswd -m /path/to/password-file.txt new-user

and type in the new password twice. (You delete users with htpasswd -D /path/to/password-file.txt old-user).

Specifying the restriction

In the directory that shall be restricted, add a file called .htaccess with the following content:

AuthType Basic
AuthName "Password Required"
AuthUserFile /path/to/passwrod-file.txt
Require valid-user

You're done. AuthType Basic means you are using a simple password file for authorization as opposed to a database entry. AuthName is printed as a message to the user. AuthUserFile specifies the full path to the password file. Require valid-user tells appache to allow only access to valid users, that is user who have been authorized (are valid).

There are a lot of configuration possibilities. Check out Authentication, Authorization, and Access Control at the apache site for more detailed informations, such as group authorization and per-directory access control.