Published April 12, 2018 by

Set Up Password Authentication in Apache on Ubuntu

In this tutorial, we will learn how to password-protect website or content on an Apache web server running on Ubuntu and Debian based server.

Install  Apache Utility Package

We will use a utility called htpasswd, part of the apache2-utils package, to create the file and manage the username and passwords needed to access restricted content.

# sudo apt-get update
# sudo apt-get install apache2-utils

Create Password File

We can use htpasswd to create a password file that Apache can use to authenticate users. We will create a hidden file for this purpose called .htpasswd within our /etc/apache2 configuration directory.

The first time we use this utility, we need to add the -c option to create the specified file. We specify a username (subhash) at the end of the command to create a new entry within the file.

# sudo htpasswd -c /etc/apache2/.htpasswd Subhash

Here it will be asked to password for the user.

Only use -c the first time you create the file. Do not use -c when you add a user in the future.

# sudo htpasswd  /etc/apache2/.htpasswd Adam

If you want to view the contents of the file, you can see the username and the encrypted password for each record

# cat /etc/apache2/.htpasswd

Configuring Apache Password Authentication

Edit Apache virtual host file 000-default.conf

# sudo vim /etc/apache2/sites-enabled/000-default.conf

Add below code to a virtual host.

<Directory "/var/www/html">
                AuthType Basic
                AuthName "Restricted Content"
                AuthUserFile /etc/apache2/.htpasswd
                Require valid-user
Save and close the file.

Restart Apache

# sudo systemctl restart apache2

Time to Test

To confirm that your website is protected, try to access your website in a web browser. You should be presented with a username and password prompt that looks like this.

If you enter the correct credentials, you will be allowed to access the website. If you enter the wrong credentials or hit "Cancel", you will see the "Unauthorized" error page.