Geoff Garbers

Husband. Programmer. Tinkerer.

Password protect a directory for a range of IP addresses

Nov 20, 2010

At work, we have a code wiki in which we keep all our database, FTP and SSH details. If someone is working from home, they’ll need to access these details from outside the office. Obviously, we can’t allow this access to be unauthenticated, as it would then be open to every Tom, Dick and Harry on the web.

So, then next logical step is to force people outside of the office to authenticate, and allow people inside the office to access it unauthenticated. I’m sure there are better ways in which to secure a site, however this suits us fine, and stops the bulk of people from viewing it.

So, first of all, let’s set up our .htpasswd file, which will contain the user credentials to use. If you haven’t yet created the file, use the “-c” argument. Otherwise, just omit it to append usernames & passwords to the file. When prompted to do so, enter the new user’s password.

htpasswd -c /path/to/htpasswd username

Now, let’s set up the .htaccess file, which will perform the act of actually authenticating users. Place this file in the directory you would like to be password-protected from outside.

Order deny,allow
Deny from all
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /path/to/htpasswd
Require valid-user
Allow from 192.168.0
Allow from 10.0.0
# Add any more IP ranges that should have access here...
Satisfy Any

AuthName refers to the display name of the authenticated area, and AuthUserFile is the absolute path to the .htpasswd file that we created. Both of these files need to be readable by Apache.

Assuming everything is followed correctly, that should be your directory now protected by a username and password from anywhere outside of your local network.