How to Block IPs from Accessing Your Website

Author:Nils Krämer
Updated:Mar 19, 2025

To block a specific IP address using Apache's .htaccess file, follow these steps:

  1. Open the .htaccess File: Locate your .htaccess file in your web server's root directory.

  2. Block a Single IP Address:

    • Add the following directives to the file under existing rules to block access from a specific IP address:
      <RequireAll>
          Require all granted
          Require not ip X.X.X.X
      </RequireAll>
      
    • Replace X.X.X.X with the actual IP address you wish to block.
  3. Allow Access for a Specific IP Address:

    • To allow access only from a specific admin IP while denying others, use:
      <RequireAll>
          Require all denied
          Require ip X.X.X.X
      </RequireAll>
      
    • Replace X.X.X.X with the IP you want to allow.
  4. Country-wide Blocking:

    • For blocking access from a specific country, use an online tool or service that generates appropriate CIDR notations for all subnets of that country. Copy and paste the generated directives into your .htaccess file.
  5. Apply Changes: After making modifications, restart your Apache server to ensure the changes take effect.

Example Configuration:

To block 192.168.1.1, add:

<RequireAll>
    Require all granted
    Require not ip 192.168.1.1
</RequireAll>

To allow only 192.168.2.3:

<RequireAll>
    Require all denied
    Require ip 192.168.2.3
</RequireAll>