How to Configure Basic Auth in Apache?

Setting up basic authentication in the Apache HTTP Server is a straightforward method for securing sensitive directories or files on your website by requiring a username and password. This article provides a step-by-step guide on how to create a password file using the htpasswd utility, configure your Apache configuration file or a .htaccess file to enforce restrictions, and restart the server to apply the changes. By following these instructions, you can quickly implement a foundational layer of security for your web applications.


Step 1: Create the Password File

The first step in implementing basic authentication is creating a secure file that stores the authorized usernames and their encrypted passwords. Apache includes a dedicated tool for this called htpasswd.

Run the following command in your terminal to create the file and add your first user. You should store this file outside of your web root directory so it cannot be accessed via a web browser.

sudo htpasswd -c /etc/apache2/.htpasswd username

Step 2: Configure Apache for Authentication

Now that your password file is ready, you need to tell Apache which directory or files require these credentials to grant access. You can configure this either in your main Apache configuration file (or virtual host file) or within a .htaccess file located in the directory you want to protect.

Open your configuration file and add the following block of directives, adjusting the directory path to match your setup:

<Directory "/var/www/html/protected-folder">
    AuthType Basic
    AuthName "Restricted Access - Please Log In"
    AuthUserFile /etc/apache2/.htpasswd
    Require valid-user
</Directory>

Here is what each directive means:


Step 3: Test and Restart Apache

Before applying the changes to a live server, it is best practice to test your configuration files for any syntax errors.

Run the following command to test your setup:

sudo apache2ctl configtest

If the output returns Syntax OK, you can safely restart the Apache service to load the new authentication rules:

sudo systemctl restart apache2

Once restarted, navigating to the protected directory through any web browser will immediately trigger a prompt asking for the username and password you configured.