News Archive
PhpRiot Newsletter
Your Email Address:

More information

Relative .htpasswd path

Note: This article was originally published at Planet PHP on 16 April 9160.
Planet PHP

Using Apache's HTTP Basic authentication is a quick and easy way to protect your website with username and passwords:

AuthType Basic AuthName "Please enter username and password" AuthUserFile /var/www/hostname/.htpasswd Require valid-user

The problem I have is that AuthUserFile is not relative to the virtual host's document root, but to the server root, which is /etc/apache2/ on Debian and Ubuntu.

Putting .htpasswd files into /etc/apache2/ is weird (and requires root access), and the only other option is to make the AuthUserFile path absolute, e.g. /var/www/hostname/.htpasswd.

Absolute paths are not portable across servers - on my dev machine, the path is /home/cweiske/Dev/html/hostname/.htpasswd, while on the server in the data center it is /home/cweiske/www/hostname/.htpasswd.

IfDefine to the rescue

Luckily, Apache provides the IfDefine directive. It's like an if statement in a programming language, but is limited to parameters that are passed to the httpd process as command line options, e.g. /usr/sbin/apache2 -Dfoo.

Now Apache is started via an init script, not via command line. Modifying the init script is also not something you want since it'll get overwritten with the next package update.

After digging around the apache2 init and configuration files, I found /etc/apache2/envvars: It allows you to set environment variables that get passed to the apache process on startup. One of these variables is APACHE_ARGUMENTS which apache2ctl passes as command line argument to the httpd process.

The solution

So the solution I am using now is the following. On my development machine, I define a development variable and activate the password check if that is not set.

I do not define a live variable because I don't always have access to the server configuration, and it also has the advantage that the password protection does still work when the server config gets reset somehow.


export APACHE_ARGUMENTS=-Ddevelopment


AuthType Basic AuthName "Please enter username and password" AuthUserFile /var/www/hostname/.htpasswd Require valid-user