How to password protect Apache site or folder but still allow some IP ranges

How to password protect Apache site or folder but still allow some IP ranges

There are cases where you’d want a particular site or subfolder to be easily accessible from specific locations (like the intranet) but apply a minimum protection from public eye of the wide internet.

Apache does support this mixed configuration for its sites through its htaccess functionality.

Create an empty .htaccess file in the root folder or subfolder of the site that you want to protect, and then add the following content to it – update the name and IP addresses / ranges as necessary.

AuthUserFile /home/mydomain/.htpasswd
AuthName "My Secret Site"
AuthType Basic
<RequireAny>
    Require valid-user
    Require ip 1.2.3.4
    Require ip 172.16
    Require ip 10.0.0.0/8
</RequireAny>

Create the .htpasswd file in a safe (not publicly accessible) location and update its path above accordingly. Add all allowed logins one per line in the username:hashedpassword format.

Generate the hash for the password using any online htpasswd generator or generate them with htpasswd on the command line:

htpasswd -nb myuser mypass
Addendum

If the .htaccess configuration appears to have no effect, the server might not be configured to allow overrides through it. You can check for this by entering gibberish in the file to trigger the Internal Server Error page to confirm file parsing.

If that is indeed the case and .htaccess is ignored, the overrides need to be enabled for the folder containing the server files or globally (not recommended) by adjusting the appropriate Directory directive in Apache’s configuration:

Per folder:

<Directory /var/www>
    AllowOverride All
    ...
</Directory>

Globally:

<Directory />
    AllowOverride All
    ...
</Directory>

See a complete Apache 2.2 to 2.4 comparison of changes and a far more extensive list of configuration cases here.

Leave a Reply