Ensure Apache 2 is installed on your system. If it’s not present, run these commands to update your package index and install the server:
apt update
apt install apache2
Enable the core Apache modules required for basic authentication and file-based user credential validation. Execute these commands, then restart the server to activate the changes:
a2enmod auth_basic
a2enmod authn_file
systemctl restart apache2
Create a encrypted credential file to store user accounts and their hashed passwords. We’ll place this file in a secure location outside the web root to prevent unauthorized access. Use the htpasswd utility to generate the file and add your first user account:
htpasswd -c /etc/apache2/.htpasswd mysecureuser
When prompted, enter a strong, lengthy password—short passwords are vulnerable to brute-force attacks, so use a combination of letters, numbers, and symbols. The htpasswd tool stores passwords as cryptographic hashes, never in plaintext.
To add additional users later, run the htpasswd command with out the -c flag (this avoids overwriting the existing credential file):
htpasswd /etc/apache2/.htpasswd anotherauthorizeduser
Modify your Apache configuration to enforce basic authentication for the target directory. Open the main configuration file at /etc/apache2/apache2.conf and update the <Directory> block for the path you want to protect (e.g., /var/www/):
<Directory /var/www/>
AddDefaultCharset UTF-8
AllowOverride None
Options All
AddHandler cgi-script .fcgi .cgi
Require all granted
AuthName "Restricted Content Access"
AuthType Basic
AuthUserFile /etc/apache2/.htpasswd
Require valid-user
</Directory>
Save the file, then restart Apache to apply the new security rules:
systemctl restart apache2
Verify the authentication setup by accessing your server’s web content. You should see a browser prompt asking for the username and password you created. Confirm that unauthenticated users are blocked from accessing the protected resources, and that valid credentials grant access.