How to password protect Apache web pages with htpasswd.

How to password protect Apache web pages with htpasswd.

If you are an Apache web sever user or if you use a web hosting service that uses Apache you can require a password to access certain folders and files on your website. Using the [htpasswd] command you will create a password file which contains usernames and passwords for entities which you want to give access.

Create a password file.

The first thing we need to do is create a password file. This file should be located somewhere on the server where your Apache2 user (www-data for Ubuntu server users) does not have direct access. You don’t want to give hackers and opportunity to download this file!

$ htpasswd -c /some/secure/folder/htpasswd someuser

New password:
Re-type new password:
Adding password for user someuser

Configure Apache2

Next, we need to tell your website to require a valid user in order to grant access to the page. You can do this two ways, the first using the .htaccess file. The .htaccess file allows users to set custom settings per web page or folder.

$ vim /var/www/cgi-bin/.htaccess

And paste into .htaccess the Auth directives which will enable password access to anything in the cgi-bin folder. Note, the AuthUserFile directive is the file we setup using the [htpasswd] command above.

AuthType Basic
AuthName “Restricted Content”
AuthUserFile /some/secure/folder/htpasswd
Require valid-user

Save the file and attempt to access a file in /var/www/cgi-bin.

You can also put the Auth directive directly into your Apache2 configuration files but .htaccess is the preferred way for most web hosting clients.

Leave a Reply