If you're running a website behind an Apache2 reverse proxy, adding a simple layer of Basic Authentication can help prevent unauthorized access. This is especially useful for internal tools, admin dashboards, or development environments.
What You Need
- Apache2 installed
- A backend service (e.g., running on localhost:8080)
- Root/sudo access
Step 1: Install Apache Tools
sudo apt install apache2-utils
This provides the htpasswd utility to manage username/password files.
Step 2: Create the Password File
sudo htpasswd -c /etc/apache2/.htpasswd mahesh
You'll be prompted to set a password. This file stores credentials securely.
Step 3: Configure the Reverse Proxy with Authentication
Edit your Apache site config
sudo vim /etc/apache2/sites-available/my-site.conf
<VirtualHost *:80>
ServerName yourdomain.com
ProxyPreserveHost On
ProxyPass / http://localhost:8080/
ProxyPassReverse / http://localhost:8080/
<Location />
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user
</Location>
</VirtualHost>
Enable the necessary Apache modules:
sudo a2enmod proxy proxy_http auth_basic
sudo a2dissite 000-default.conf
sudo a2ensite my-site.conf
sudo systemctl restart apache2
Now, anyone visiting your site will be prompted to log in with a username and password.
Enable HTTPS for Security
Basic Authentication over HTTP sends credentials in plain text. It is strongly recommended to enable HTTPS to secure the traffic.
To set up HTTPS with Let’s Encrypt:
sudo apt install certbot python3-certbot-apache
sudo certbot --apache -d yourdomain.com
Now your reverse proxy is secured with both password protection and SSL encryption.