Apache’s configuration allows access to be restricted by IP address in both the main configuration file, virtualhost directives and .htaccess files. It can be useful to deny access to specific IP addresses, for example to keep a bad robot out; and it can equally be useful to deny access to all IP addresses but allow a select few in, for example to restrict access for a specific area of a website (e.g. the admin) to a specific number of IP address. This post shows how to do both.
Add the following rules, customized to suit your specific circumstances to an either already existing .htaccess file or to a new one if one doesn’t already exist.
If you want the rules to apply to the entire site, then put the .htaccess file at the root level.
To deny/allow access to a specific directory only, put the .htaccess file in that directory only.
Denying access to specific IP address(es)
To deny access to a single specific IP address, in this example 192.168.1.16:
deny from 192.168.1.16
You can also have multiple deny from lines, in this example to deny access to visitors from 192.168.1.16 and 192.168.1.17:
deny from 192.168.1.16 deny from 192.168.1.17
To block the whole range from e.g. 192.168.1.1 to 192.168.1.255 leave the last number off, e.g.:
deny from 192.168.1
And you can also use netmask ranges. I won’t pretend to have a very good understanding of how netmask ranges work but this example would block access from 192.168.1.1 to 192.168.1.14:
deny from 192.168.1.1/28
There are many online IP address calculators that can be used to work out these ranges.
Denying access to all but specific IP address(es)
It can be useful when testing a website before launch or on a staging site to not let anyone in except for a few specific IP address. Another pssibility is to restrict access to particular parts of a website (e.g. an admin area) to specific IP addresses.
This is easy to do as well. The example below denies access to everyone except for 192.168.1.16:
deny from all allow from 192.168.1.16