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 10.0.
</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

Leave a Reply