TL;DR
Your basic authentication is working when accessed directly but failing from different IPs because your web server isn’t correctly passing the necessary headers. This guide shows how to fix it, usually involving Apache or Nginx configuration.
Solution Guide
- Understand the Problem
- Basic authentication relies on sending credentials (username and password) with each request.
- Web servers often cache authentication information, but this can cause issues when accessed from different IPs if headers aren’t handled correctly.
- The server might be rejecting the authentication attempt because it doesn’t recognise the headers sent from a new IP address.
- Check Your Web Server Configuration
The most common culprits are Apache or Nginx. We’ll cover both.
- Apache Configuration
- Edit your
.htaccessfile or the relevant virtual host configuration file (usually in/etc/apache2/sites-available/). - Ensure you have a section like this for basic authentication:
AuthType Basic AuthName "Restricted Area" AuthUserFile /path/to/.htpasswd Require valid-user - Edit your
- Crucially, check for header caching directives. Look for lines like
Header always set Cache-Control "no-cache"or similar. If present, make sure they apply to the authentication headers as well. - Restart Apache:
sudo systemctl restart apache2 - Nginx Configuration
- Edit your Nginx configuration file (usually in
/etc/nginx/sites-available/). - Ensure you have a section like this for basic authentication:
auth_basic "Restricted Area"; auth_basic_user_file /path/to/.htpasswd; - Edit your Nginx configuration file (usually in
- Check for proxy caching. If you’re using Nginx as a reverse proxy, ensure it isn’t caching authentication responses. Look for
proxy_cache_validdirectives and adjust them if necessary to avoid caching authenticated content. - Restart Nginx:
sudo systemctl restart nginx - Verify .htpasswd File Permissions
- The
.htpasswdfile should have restricted permissions (e.g., 600 or 640). This prevents others from reading the usernames and passwords.
chmod 600 /path/to/.htpasswd - The
- Test Thoroughly
- Access the protected page directly (the IP address that works).
- Access the protected page from a different IP address.
- Clear your browser cache between tests to ensure you’re not using cached credentials.
- Check Server Logs
Examine your web server’s error logs (usually in
/var/log/apache2/error.logor/var/log/nginx/error.log) for any clues about the authentication failure. Look for messages related to invalid credentials, header issues, or file access problems.

