Apache makes it easy to quickly setup username and password authentication using htaccess.  In this tutorial, we'll cover the basics of enabling authentication for any directory that Apache is serving.  In this example, we'll create and lock a new folder.

The only requirement for this tutorial is the Apache web server running on some *nix.

Create a directory in your served content that you'd like to lock.  Assuming no changes have been made to your default Apache setup, that's probably at '/var/www/html/'.  In this example, we're serving a directory located at '/var/www/html/example/'.  We'll create a folder called 'secrets' and lock it.

Create the folder you want to lock:

$ cd /var/www/html/example
$ sudo mkdir secrets

Change the ownership to your web user (the user Apache runs as, by default 'www-data'):

$ sudo chown www-data:www-data secrets

Enter your new folder, and create a file called .htaccess:

$ cd secrets
$ sudo vi .htaccess

Edit the .htaccess file to contain the following lines:

AuthName "Yes?"
AuthUserFile /etc/apache2/.htpasswd
AuthType Basic
Require valid-user

Each line explained:

  • 'AuthName' is the string that Apache will prompt the user with
  • 'AuthUserFile' is the location of the username and password to validate against
  • 'AuthType' specifies the type of authentication ('Basic' is implemented by mod_auth_basic)
  • 'Require' allows conditional access restrictions (eg. by IP range, by HTTP header)

Because all Apache (running as www-data) needs to do is read the file, we can leave it as owned by root.

Last, we need to create the password file which in accordance with the 'AuthUserFile' directive:

$ sudo htpasswd -c /etc/apache2/.htpasswd <username>

Enter a password for your locked folder and then re-enter the same password:

Create htpacces pasword file

htpasswd comes with Apache and takes care of salting/hashing your password. -c tells htpasswd to create a new file.

There should be no need to restart Apache after htaccess changes.  Simply navigate your browser to the locked page (ie. 'yoursite.com/secrets'), and you'll be prompted for a username and password.  Enter the credentials you just setup and you're good to go! 

In Firefox, the final result will look like this:

htaccess authorization window in Firefox

 

# Reads: 1328