Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

How to Block IP Ranges with `.htaccess`

1 min read .
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>
  • /24 corresponds to the subnet mask 255.255.255.0, covering 256 IPv4 addresses.
  • This rule blocks every address from 192.168.1.0 through 192.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.0 through 10.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

  1. Apache version → The Require syntax applies to Apache 2.4+. Apache 2.2 used the older Deny from and Allow from directives.
  2. Avoid extremely large rule sets.htaccess is processed during requests. If you need to block thousands of addresses, a firewall such as iptables, nftables, or ufw, or a WAF, is usually a better fit.
  3. 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).

Related Posts

chevron-up