How to use htaccess to password protect your website

There are many reasons why you would want to password protect your website, or a section of your website. For example, your website could be under development and should only be accessible by yourself or your clients. Or you may want to limit access to an admin area or a photo gallery.

If your website is served via the Apache web server, password protecting specific areas can be implemented quite easily using a .htaccess file. The process consists of two parts. The first step is to generate a password file. The second step is to implement the rules and reference the file.

Step 1: Creating the password file

To create the password file you should use the htpasswd command line tool. This is usually installed as part of the Apache web server.  SSH in to your server and run the following command:

Where <username> is the name you want to use in the ‘User name’ section of the login prompt. When you hit enter it will prompt you for a password, and then ask you to confirm it. Note that you won’t see anything on the screen when you enter your password.

When this is done your password will be encrypted in the .htpasswd file. To see this, use the cat command:

For security reasons you MUST keep this file OUTSIDE of your website public directory.  A good place to put this is one directory above your web directory. E.g, if your website is served from /home/username/public, your password file would live at /home/username/.htpasswd.

Step 2: Adding the htaccess password protection

Now that you’ve created the password file you can set up the htaccess file to handle the password protection.  Inside your website public directory, either create or edit the .htaccess file and add the following:


Save the file and browse to your website – you should get a prompt asking for your Username and Password:
If you wanted to password protect a specific directory on your website, simply create or edit the .htaccess file inside the directory and add the code above.