How to Block IP Ranges with `.htaccess`
One useful feature of Apache is the flexibility of .htaccess. In addition to URL rewriting and caching rules, .htaccess can also restrict access based on IP addresses.
If you are dealing with spam bots, brute-force attempts, or unwanted traffic from a particular network, one quick option is to block an individual IP address or an entire range.
Block a Single IP Address
To block one IP address, use:
<RequireAll>
Require all granted
Require not ip 192.168.1.100
</RequireAll>This blocks 192.168.1.100 while allowing other clients to access the site.
Block an IP Range
To block a complete range such as 192.168.1.0 through 192.168.1.255, use CIDR notation:
<RequireAll>
Require all granted
Require not ip 192.168.1.0/24
</RequireAll>/24corresponds to the subnet mask255.255.255.0, covering 256 IPv4 addresses.- This rule blocks every address from
192.168.1.0through192.168.1.255.
Practical Examples
-
Block a larger range:
<RequireAll> Require all granted Require not ip 10.0.0.0/16 </RequireAll>This blocks
10.0.0.0through10.0.255.255. -
Block several addresses or subnets:
<RequireAll> Require all granted Require not ip 203.0.113.25 Require not ip 198.51.100.0/24 Require not ip 192.0.2.0/28 </RequireAll> -
Allow only specific addresses instead:
<RequireAny> Require ip 203.0.113.5 Require ip 203.0.113.6 </RequireAny>Every address not listed is denied.
Important Notes
- Apache version → The
Requiresyntax applies to Apache 2.4+. Apache 2.2 used the olderDeny fromandAllow fromdirectives. - Avoid extremely large rule sets →
.htaccessis processed during requests. If you need to block thousands of addresses, a firewall such asiptables,nftables, orufw, or a WAF, is usually a better fit. - Test before production → A mistake in an access rule can lock out legitimate users or administrators, so validate the configuration before deploying it broadly.
Conclusion
Blocking individual IP addresses or CIDR ranges with .htaccess is a convenient way to stop unwanted traffic at the Apache layer. It works well for small to medium rule sets, while larger-scale filtering is better handled by a firewall or Web Application Firewall (WAF).