Allow / Block Access to Site Based on IP address

Print Page

It can be useful to deny public access to a website while still allowing the administrator access; it can be equally useful to deny access to some specific IP addresses, for example to keep a bad robot out.

Apache’s configuration allows access to be restricted by IP address with .htaccess files. This post will show how you how to do both.

Allow Access to a Certain IP

order deny,allow
deny from all
allow from 12.34.56.78

The first line “order deny,allow”  tells the web server the “Order” in which Allow and Deny directive will be evaluated. It says: all access is denied by default but still allow access to users in the Allow list.

The default Apache order is deny,allow. So you can skip the first line in your .htaccess file if you do not need to change the order in which the Deny and Allow rules are being evaluated by the web server.

Allow Access from Multiple IP Addresses

order deny,allow
deny from all
allow from 12.34.56.78
allow from 12.34.56.79

Another way to specify:
allow from 12.34.56.78 12.34.56.79

Separate IP addresses with a space.

Deny Access to a Certain IP

order allow,deny
deny from 12.34.56.78
allow from all

With “order allow,deny” Allow list is looked up first and then the web server checks the deny from list. Here the web server is ordered to allow access to all hosts but not to those that are present in the “Deny from” list.

Deny Access from Multiple IP Addresses

order allow,deny
deny from 12.34.56.78
deny from 12.34.56.79
allow from all

Deny Access to An Entire IP Block/Range

deny from 12.34.56

This will refuse access to any user with an address in the 12.34.56.0 to 12.34.56.255 range.

Deny Access to a Domain or Sub-Domain

In addition to numeric addresses, users can also be denied access by using domain names and sub-domain names.

deny from isp.com

This would deny access to all users connected to the internet via isp.com from viewing your site.