Apache/.htaccess

< Apache

Principle

In order to protect a directory in particular (and its subdirectories), it suffices to place a file called .htaccess inside. Apache will instantly apply its rules after, only in this tree structure.

Attention: the Windows explorer doesn't allow to name some files beginning by a dot, but a text editor is able to save as .htaccess.

For example, to forbid to visualize a directory files which hasn't got any index (eg: .html, .php), add the code: Options -Indexes.

Protection by provenance

Numerous robots uses to try to crack some databases (for instance via PhpMyAdmin). To protect from them, it's possible to authorize only two IP to read the directory:

deny from all
allow from 127.0.0.1
allow from 127.0.0.2

If the authorization ranges have some addresses in common with the prohibited ranges, it's better to specify their precedence (the lines order in the .htaccess file doesn't change anything):

order allow, deny 
begin by the authorizations and then start the interdictions, by risking to ban what was previously allowed.
order deny, allow 
the contrary is less restrictive.

Protection by password

Authentication configuration

It's imperative to allow the authentication parameters modifications in the Apache settings.

The directive AllowOverride of a parent directory must contain the option AuthConfig.

The directives to place in the .htaccess are:

AuthType basic
authentication type communally adopted but poorly secured.
AuthName "My message"
the text as an invite in the dialog box.
AuthUserFile /etc/apache2/my_passwd
the passwords file path.
Require valid-user
specifies that a valid account is needed to accede to the folder.

We can also use Require user toto sasa to authorize only the two accounts toto & sasa.

The authentication type basic uses not crypted passwords.

Some other more secured types exist, like digest, which is recommended to combine with HTTPS.

The first request is addressed to the protected directory and provokes the displaying of the dialog box, from which the user should identify (with login and password):

Passwords file

The following command creates a passwords file called with one user toto:

htpasswd -c /home/user/www/.htpasswd toto

To add or modify a user:

htpasswd /home/user/www/.htpasswd sasa

Then, tell to .htaccess the .htpasswd path with:

AuthName "Protected page"
AuthType Basic
AuthUserFile "/home/user/www/.htpasswd"
Require valid-user

Redirections

The syntax is the same as the general URL rewriting, unless it will only affect the .htaccess directory.

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.