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- The
-cflag tells the utility to create a new file. Only use this flag for the very first user; omitting it allows you to append additional users to the same file later. - Replace
usernamewith the actual username you want to grant access to. - You will be prompted to enter and confirm a secure password for the user.
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:
- AuthType Basic: Specifies that you are using the basic HTTP authentication method.
- AuthName: The message or realm name displayed to the user in the login prompt pop-up window.
- AuthUserFile: The absolute file system path to the password file you created in Step 1.
- Require valid-user: Ensures that any user listed in the password file who provides a correct password can gain access.
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 configtestIf the output returns Syntax OK, you can safely restart
the Apache service to load the new authentication rules:
sudo systemctl restart apache2Once restarted, navigating to the protected directory through any web browser will immediately trigger a prompt asking for the username and password you configured.