Using .htaccess for password protecting your folders

If you need to have certain areas (folders or files) of your web site protected you can use .htaccess and .htpasswd files to enable a basic user/pass protection.

The Apache web server provides a quick and easy way to protect a file or folder on your site.

The password protection depends on two files. The first one is the .htaccess file. It tells the webserver that viewing the file and/or folder requires authorization. The second file is the .htpasswd file it stores information about the users and their passwords. Its content will look similar to the following line:

webuser:qkbPmuht5Gzgc

The first part is the username, the second part of the line after the colon symbol is the password. The password is encrypted either using a modified version of MD5 or the system crypt() function.

Creation of the .htpasswd file is usually handled by the Apache htpasswd command line utility.
In case you do not have access to it on your server, you can use the following form to generate your .htpasswd file.

It is recommended that the .htpasswd file is located in a folder that is not accessible through the web. However most servers retrict acces to these files in their setup.

Once you have the .htpasswd file ready you need to create a file named .htaccess and place it in the folder you wish to have protected. The file should have the following lines

AuthType Basic
AuthUserFile "/home/username/path_to_htpasswd/.htpasswd"
AuthName “Enter valid username and password!”
require valid-user

The line AuthUserFile tells the web server where to look for the file containing the usernames which are allowed to access the folder.

The AuthName is what is printed in the user/prompt of the visitor’s browser.

Protecting a single file is a little tricky, you will need to add some more lines to the .htaccess file. Let’s say you wish to protect a file named “my-secret-file.html”. Then you will need to following .htaccess:

AuthType Basic
AuthUserFile "/home/username/path_to_htpasswd/.htpasswd"
AuthName "Enter valid username and password!"
<Files my-secret-file.html>
require valid-user
</Files>

The .htaccess file should be located in the same folder where the my-secret-file.html is located.