Home : Internet : Web Development : Security : Password Protection

How to Password-Protect Web Pages

This page shows how to use .htaccess and .htpasswd files to protect web pages and directories with a username/password. These instructions are for an Apache server running on a Linux system (sorry but we don't have instructions for Windows servers).

Note: Many people get confused by the dot (AKA period or full stop) and the lack of file extension in the names .htaccess and .htpasswd. The answer is that the names always begin with a dot, and htaccess/htpasswd are the file extensions. There is no normal file name before the extension. This can be confusion for Windows users (and the Windows operating system) but there are good reasons for using this convention. Once you get used to it, it's fine.

.htaccess and .htpasswd files are plain text files which can be placed in any directory of your web site. Note that .htaccess files have many uses — password-protection is only one. It is common to use the same .htaccess file for more than one purpose.

To protect a directory you need to create and upload the .htpasswd file, then the .htaccess file. Everything within the same directory as the .htaccess file will be protected.

The .htpasswd File

First, create a text file and name it .htpasswd. Enter the usernames and passwords, each on a separate line and delimited by a colon like so:

Dave:aatn0reZcpJ6s
Sam:aaFarHdJV6Qw2
Sharon:aatuPo4FOPXBQ

You will notice that the passwords in this example appear to be random letters and numbers — that's because they are encrypted. All passwords must be encrypted like this in the .htpasswd file, but users still enter the original password when prompted. There are several ways to encrypt passwords but the easiest method is to use our online password encrypter.

Once your password file is ready, upload it to a safe place on your website. It doesn't matter where it goes but we recommend that you place it outside your web space (e.g. above the public_html or www folder).

The .htaccess File

The next step is to create a .htaccess file in the directory you want to protect. If you already have one, add the following text to it. Otherwise, create a new file and enter this text:

AuthName "Name of Protected Area"
AuthType Basic
AuthUserFile /full/path/to/.htpasswd
Require valid-user

There are two things you need to change (highlighted in red):

  1. AuthName: The name of the protected area. This can be any name you like, e.g. "Members Area" or "Admin Page".
  2. AuthUserFile: This is the full server path to the .htpasswd file. If you don't know what this is you may need to contact your server administrator, or consult the help files for your hosting package. It will typically be in the form "/home/username/" or something similar.

Notes:

Subscribe to us on YouTube