In this lesson we will password protect a directory using .htaccess.
This can be extremely useful for controlling access to sensitive or restricted areas such as member or administration directories.
How to Create a .htpasswd file
The first thing we need to do is create a file called .htpasswd and store it in a non-public location.
This file will contain the username and password of each valid user allowed to have access to our password protected directory.
The format of the file is simply a list of usernames and passwords. We start with the username, then a colon (:), then the encrypted password. Each user must be placed on a separate line as follows:
In the case above, the username and passwords are:
USERNAME: paulsmith
PASSWORD: password
USERNAME: sam
Password: 123456
You will need to generate encrypted passwords. If you are unsure how to do this then you can use one of the many .htpasswd generators on the web.
How to Create a .htaccess file
Go to the directory you wish to password protect and create a new file in it called .htaccess. Note that the dot in front of htaccess is required.
The .htaccess file should contain the following 4 lines of code:
Line 1: this is simply specifying which authentication module to use.
Line 2: this will form part of the message in the popup window that will appear to the user when they visit the password protected directory.
Line 3: you must enter the full path to the .htpassword file. Rememeber, the password file should be stored in a non-public directory.
Line 4: we are specifying that we will allow access to any valid user.
How to Require a Specific User in .htaccess
In the example above we allowed access to any valid user.
It is possible to only allow access to a specified user as follows:
Line 4: in this case we have specified that we want to only give access to paulsmith.