How to Block an IP Address or Range Using .htaccess

If you need to block specific IP addresses or ranges from accessing your website, you can do so using rules in the .htaccess file. This is especially useful for preventing unwanted visitors, bots, or malicious activity.


1. Blocking a Single IP (Apache 2.4+)

To block a specific IP address, add the following lines to your .htaccess file:

<RequireAll>
    Require all granted
    Require not ip 123.45.67.89
</RequireAll>
  • Replace 123.45.67.89 with the IP you want to block.
  • Any request from that IP will receive a 403 Forbidden error.

2. Blocking Multiple IPs

You can block multiple IP addresses by adding more Require not ip lines:

<RequireAll>
    Require all granted
    Require not ip 123.45.67.89
    Require not ip 98.76.54.32
    Require not ip 192.168.1
</RequireAll>
  • The above blocks:
    • 123.45.67.89
    • 98.76.54.32
    • All IPs starting with 192.168.1 (entire range)

3. Blocking an IP Range Using CIDR Notation

If the unwanted traffic comes from a range of IPs, use CIDR notation:

<RequireAll>
    Require all granted
    Require not ip 123.45.67.0/24
</RequireAll>
  • /24 means the first 24 bits are fixed, so this will block all IPs from 123.45.67.0 to 123.45.67.255.

4. CIDR Quick Reference Table

CIDR Number of IPs Blocked Example Range
/8 16,777,216 123.0.0.0 – 123.255.255.255
/16 65,536 123.45.0.0 – 123.45.255.255
/24 256 123.45.67.0 – 123.45.67.255
/32 1 123.45.67.89 (single IP address)

5. Apache 2.2 and Older Syntax

If your server uses Apache 2.2 or earlier, use:

order allow,deny
deny from 123.45.67.89
deny from 123.45.67.0/24
allow from all

6. Things to Keep in Mind

  • Always back up your .htaccess before making changes.
  • Be careful when blocking ranges—you might unintentionally block legitimate users.
  • After editing .htaccess, clear any caching (server or CDN) to apply changes immediately.
  • If you have access to your hosting control panel or server firewall, IP blocking at the server or firewall level is more efficient than using .htaccess.

Tip: For frequent attacks, consider using a firewall service like Cloudflare or ModSecurity for better performance and protection.

Was this article helpful?
YesNo