Home / Password protection with Apache but allow from an IP address

Password protection with Apache but allow from an IP address

I have posted how to password protect a directory and remove password protection from a subdirectory with Apache and in this post look at how to have a password for all users except those from a defined IP address or set of IP addresses.

Basic password protection

Refer to the full post about password protection for all the examples and details, but here’s a quick look at how to add the appropriate lines to an .htaccess file or a <Directory> or <Location> block within the main Apache configuration:

AuthUserFile /path/to/.htpasswd
AuthName "Restricted Access"
AuthType Basic
require user [username]

Allowing users in from an IP address

If you don’t want to prompt users from a particular IP address or group of IP addresses then this can be enabled while still asking for a username and password from everyone else.

This can be useful if you want to allow access from your office or someone else’s business location when they have a stactic IP address, or even if you have some automated bot on a server that you don’t want to have to code the logic in for passing along the username and password.

To do this, add “satisfy any”, “deny from all” and “allow from xxx.xxx.xxx.xxx” lines to the above example as shown below. In the example below, we allow access from 192.168.1.1 to 192.168.1.255, 10.1.1.45 and 172.16.5.106.

AuthUserFile /path/to/.htpasswd
AuthName "Restricted Access"
AuthType Basic
require user [username]
satisfy any
deny from all
allow from 192.168.1.
allow from 10.1.1.45
allow from 172.16.5.106

The IP addresses can also be done on a single line like so:

AuthUserFile /path/to/.htpasswd
AuthName "Restricted Access"
AuthType Basic
require user [username]
satisfy any
deny from all
allow from 192.168.1. 10.1.1.45 172.16.5.106