How to Password Protect a Directory with htaccess
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.
Creating the .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:
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.
Creating the .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:
AuthType Basic AuthName "Password Protected Area" AuthUserFile /full/path/to/.htpasswd Require valid-user
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.
Requiring a Specific User
In the example above we allowed access to any valid user.
It is possible to only allow access to a specified user as follows:
AuthType Basic AuthName "Password Protected Area" AuthUserFile /path/to/.htpasswd Require user paulsmith
Line 4: in this case we have specified that we want to only give access to paulsmith.
Want to Learn More?
Become a member and get access to the member only area of this site here.
Your email address will not be published.
PHP for Beginners
PHP, MySQL and PDO
Coming soon, a full course on using PHP, MySQL and PDO. Be notified as soon as the course goes live.