Really simply HTTP Authentication on Apache

Apr 7, 2012

Apache How-toThere are countless reasons for using some kind of HTTP Authentication on your website but the one I come across most often is to password protect a new site until the client is happy for it to go public. For this kind of situation I usually use the Apache mod_auth_basic module because it is quick and easy to set-up and equally quick to remove once you are ready for the site to be public. Not to mention that there are no changes to your codebase and so it can be applied just to the live server without risk of breaking anything in the site.

So, how do we acheive this? The documentation for this is actually split over two pages in the apache docs, one for the mod_auth_basic and one for the specific file based method mod_authn_file. But unless you already know how to do this the two documents don’t make a lot of sense.

There are two parts to setting this up, firstly you need to create a file with usernames and passwords in it. There is a utility, htpasswd, for doing just that as part of the Apache intall, you should find it in the same directory as your apache binary, in Ubuntu this is actually part of your path so you can call it from anywhere. Parameters are the password file and the user to create – with a flag of -c to create the file in the first instance, see the example below fromt he docs.

htpasswd -c newpasswordfile username1

htpasswd existingpasswordfile username2

Once you have done that you just need to configure Apache to do the authentication. This can be done inside an Apache Directory directive, or from a .htaccess file.

AuthType basic
AuthName "private area"
AuthBasicProvider file
AuthUserFile /path/to/existingpasswordfile
Require valid-user

Simple as that. Make sure the password file isn’t in one of your public folders of course! And be aware that this method does send the password across the internet as clear text. For more robust security you might want to look at mod_auth_basic’s big brother [mod_auth_digest][3].

[3]: http://httpd.apache.org/docs/2.2/mod/mod_auth_digest.html