How to Set Up Apache Password Authentication on Ubuntu 18.08?

Almost all applications on the internet have some parts that should be protected with a password, like the directories which store confidential documents, pdf files, etc. 

This article will show you how to protect these directories on the server level with Apache htpasswd.

What is htpasswd?

Apache htpasswd is an Apache utility that allows you to protect a part of your application or the whole application with a username and password.

Follow the steps below to set up the htpasswd on your Ubuntu server –  

  • Install Apache2 utils 

It is easy to install apache2 utils. You can do it by executing the following commands on your terminal – 

$ sudo apt-get update

$ sudo apt-get install apache2-utils

Create Apache htpasswd file

Once the installation is done, we need to create an htpasswd file to store the user information. 

$ sudo touch /etc/apache2/.htpasswd

Once the file is created, we can use the users to the htpasswd file. We can create multiple users for multiple applications.

Add htpasswd user

Adding a user to htpasswd is pretty simple; you need to execute the following command to add the user –  

$ sudo htpasswd /etc/apache2/.htpasswd USERNAME

Once you enter the above command, it will ask you to set a password for that user twice.
Just enter the strong password, and you are good to go. 

Setup Apache htpasswd protection with VirtualHost

VirtualHost file will ask the Apache web browser to redirect the request to the specific document root on the domain name.
Here, we will add a few lines of code to make the specific directory password protected, for which you will have to run this command –  

$ sudo nano /etc/apache2/sites-available/000-default.conf

Make sure you have the below-given code inside –  

<VirtualHost *:80>
ServerAdmin webmaster@localhost

DocumentRoot /var/www/html/test

ErrorLog ${APACHE_LOG_DIR}/error.log

CustomLog ${APACHE_LOG_DIR}/access.log combined

<Directory "/var/www/html">

      AuthType Basic

      AuthName "Restricted Content"

      AuthUserFile /etc/apache2/.htpasswd

      Require valid-user



With this, the test folder will be password protected.

Now access the folder from the browser, and you will see that it will ask for the password.

Was this answer helpful?

« Back