This article describes an easy way to password protect a web directory in Apache using an .htaccess file. Note: this tutorial is done on a Ubuntu server with Apache installed.

Installing the Apache Utilities Package

First, you need to install the apache2-utils package which provides a utility called htpasswd to create a password file. You can install it by running the following command:

Configure Apache to Allow .htaccess Authentication

By default, Apache doesn’t allow the use of an .htaccess file in Ubuntu 14.04. You will need to set up the Apache config file to allow .htacces- based authentication. You can do this by editing the Apache config file: Find the section that begins with the Directory “/var/www/html” and change the line from AllowOverride none to AllowOverride AuthConfig Save and close the file.

Create the Password File

You can use the htpasswd command line utility to create a password file that Apache can use to authenticate users. Now, create a hidden .htpasswd file in the “/etc/apache2” configuration directory. This will ask you to supply and confirm a password for authuser1. If you want to add another user, then leave out the -c argument with htpasswd command. Now, to create another authentication for a second user, authuser2: You can see the user name and the encrypted password for each record by running:

You need to grant permission to the “www-data” user to be able to read the .htpasswd file.

Configure Apache Password Authentication

You need to create an “.htaccess” file in the web directory you wish to restrict. In this example I will create an “.htaccess” file in the “/var/www/html/” directory to restrict the entire document root. Add the following content: Here is what the above code means:

AuthType: This option defines the type of authentication. AuthName: This is content which displays on web page when prompted for user name and password. AuthUserFile: This option specifies the location of user credentials. require valid-user: This indicates that only successful authenticated requests may load the page.

Save and close the file, and restart Apache to make these changes take effect.

Testing Password Authentication

Now on a remote machine, access your website in a web browser. You will be prompted with a user name and password to access web page.

If you enter the correct user credentials, you will be allowed to access the content. If you enter the wrong user credentials or hit “Cancel,” you will see the Unauthorized error page.

Conclusion

You should now have enough knowledge to set up basic authentication for your Apache web server. Also remember that password protection should be combined with SSL encryption so that your credentials are not sent to the server in plain text.