Davide Muzzarelli

Apache mod_rewrite and directories protected by password

As a web site developer, when I use a server side script (like a FCGI, PHP, ASP ecc.) I activate the mod_rewrite in order to convert the urls in a pretty format.

So, an url like this:


…could be converted like this:


This is very good for SEO and just for the simplicity of the url.

In order to activate this, is simple to add this code in the “.htaccess” file in the root directory of the web site:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-fRewriteRule ^(.*)$ index.php?page=$1 [QSA,L]

The first line activate the mod_rewrite. The second one control if the url is not a real file on the web server, and the last one convert the url.

Actually it is not so complicated. But try to add a sub-directory protected by password and some problems will arise.

Make a directory “foo”, put a file under it like “index.html” in order to test the behavior and protect it with this “.htaccess” file:

AuthName "Restricted Area"AuthType Basicrequire valid-userAuthUserFile "/home/foobar/passwd"

This code will protect that directory with a password (contained in the “passwd” file in another directory of security reasons).

Try to access to it and you will discover that it is impossible to use. The problem is the mod_rewrite because it rewrite also the url of this directory and it can’t see the index.html file because it is hidden by the password. Without the password protection the file is well displayed…why?? :(

In order to solve this problem you have to add two lines to your root .htaccess file:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-d [OR]RewriteCond %{REQUEST_URI} ^/$RewriteRule ^(.*)$ index.php?page=$1 [QSA,L]

The first line added control if the url is a valid directory into the filesystem, it add a OR condition, and the second line force the void url (in this case is “http://www.foobar.it/) to convert itself with mod_rewrite. The home page will not be displayed without that second line.

Now it is possible to see the directory “foo” and access to the index.html but…only if you are just logged in. If you are not logged in you will be redirect to a 401.html page redirected again to the index.php file (only a little debug system can show this to you); so the login form is not displayed, and this is a big problem.

In order to force the login form, it is sufficient to add this last line in the “foo/.htaccess” file:

AuthName "Restricted Area"AuthType Basicrequire valid-userAuthUserFile "/home/foobar/passwd"ErrorDocument 401 default

Now the login form is forced and you can use it without problems.

Dicci Cosa Pensi

Lascia un commento qui sotto...

Confermando l'invio accetti di aver letto le note legali e di aderire ad esse.