Blocking HTTP requests via Iptables for a specific domain

In a previous article, we showed how to block specific domains at the DNS level using iptables. Today, we will expand into that and show how to also block HTTP requests for a specific domain (or URL) in there.

IPTables String Matching

Iptables string matching is very powerful and easier to use than the hex-string module we used before. When you specify -m string –string, it will activate the string module and inspect at the packet content for the keyword you are looking for.

HTTP Packet

If you ever looked inside a HTTP packet, it is divided by multiple headers, generally something like:

User-Agent: Mozilla/5. ...

Where the GET (or POST) /URL has the page you are visiting and the Host: header has the domain name. With that in mind, we can easily create our iptables rule.

IPTables Blocking

First, let's block HTTP generally runs on port 80, so we restrict our pattern matching only to that port:

/sbin/iptables -I INPUT -p tcp --dport 80 -m string --string "Host:" --algo kmp -j DROP

That way every HTTP request going to, will be blocked.

Iptables blocking

We can expand our rule to have multiple string matches if also want to block a specific URL. For example, if we wanted to block /admin on, that's how we would do it:

/sbin/iptables -I INPUT -p tcp --dport 80 -m string --string "Host:" --algo kmp -m 
string --string "GET /admin" --algo kmp -j DROP

Posted in   Networking_Tips   Troubleshooting   Linux   Firewall   IPTables     by noc_team

Improve Your Websites Speed and Security