Blocking IP Addresses Using htaccess

I’m writing this because blocking by domain on my hosts pretty much kills my web site and so I have had to learn to block ip addresses. Blocking single ip addresses is simple as you just need something like the following

order allow,deny
deny from 9.120.161.206
allow from all

And that will block the computer at ip address 9.120.161.206 from being able to access your site. But what if you want to block a whole range of ip addresses such as 9.120.161.0 to 9.120.161.255? Well then we just leave off the end number like this

order allow,deny
deny from 9.120.161.
allow from all

Ok so now we get to the clever and damn fiddly bit. As of Apache 1.3 we can use CIDR codes to specify ranges of ip addresses. So another way of writing the above code would be

order allow,deny
deny from 9.120.161.0/24
allow from all

and that would do exactly the same as 9.120.161. but we can do so much more. After the break (ie click the read more link) I will show a list of the CIDR codes and what they do.

Ok first thing we need to do is explain that CIDR goes from 0 to 32. 0 covers every possible ip address, all 4,294,967,296 of them so doesn’t really get used much. As CIDR is based on bits the number of ip addresses blocked doubles as we go down the list.

32 only block the single ip address so is a bit pointless
31 blocks 2 address so would block 127.0.0.1 and 127.0.0.2. Could just as easily be like 127.0.0.19/31 as you can start from any ip address
30 blocks 4 ip address so 127.0.0.1 to 127.0.0.4
29 blocks 8 ip address so 127.0.0.1/29 would block 127.0.0.1 to 127.0.0.8 (starting to see a pattern?)
28 down to 25 I’m sure you can figure out. It’s from 24 it gets interesting.
24 blocks a whole sub set of ip addresses (thats 256 addresses) so we can use 127.0.0.0/24 to block 127.0.0.0 to 127.0.0.255
23 blocks 512 address so that’s 2 entire subsets. 127.0.0.0/23 would block 127.0.0.0 to 127.0.1.255
22 is 1024 addresses or 4 sub sets
21 is 2048 or 8 sub sets
20 is 4096 address or 16 sub sets (like 127.0.0.0 to 127.0.15.255)
19 would be 8192 address so 32 sub sets. I used this one when blocking keyweb.de servers
18 is 16384 or 64 sub sets
17 equals 32768 addresses and I used it to block some layeredtech
16 is the lowest CIDR code I have used and that covers 65536 addresses or 256 sub sets. This is again used to block LayeredTech.

I’m pretty sure you can work the rest out for yourself from here on. I got my information from this Wikipedia entry. I will now post a couple I have used in my own htaccess and say why.

# These two are for layeredtech. Well known friend to spammers.
deny from 72.232.0.0/16
deny from 72.233.0.0/17
# Keyweb.de servers. Plenty of spam attempts from them
deny from 87.118.96.0/19
# Dragonara.net just started getting spam attempts from them
deny from 194.8.74.0/23

Leave a Reply