Block access from selected IP addresses or countries

Block individual IP addresses, IP ranges or countries in .htaccess using Require rules and the X-Country-Code header.

You can use .htaccess to block access to your website from individual IP addresses or IP ranges.

Simply add the relevant lines to your webhosting’s .htaccess file.

IP addresses

The following syntax can be used to block IP addresses:

<RequireAll>
Require all granted

# Block single IP
Require not ip 192.0.2.1

# Block IP range
Require not ip 192.0.2.0/24

# Block IP range
Require not ip 192.0.2
</RequireAll>

And if you want to block all access except from certain IP addresses:

Require ip 69.46.36.0/27
Require ip 192.0.2.1

See also https://httpd.apache.org/docs/2.4/howto/access.html#host

Block countries

Our web server adds an X-Country-Code header to incoming requests, which you can use to filter on. This header cannot be spoofed by others.

If you want to block access from selected countries, you can use this:

# Block CN, RU and KP
SetEnvIf X-Country-Code "^(CN|RU|KP)$" blocked_country
<RequireAll>
  Require all granted
  Require not env blocked_country
</RequireAll>

And if you only want to allow specific countries:

# Allow DK SE NO
SetEnvIf X-Country-Code "^(DK|SE|NO)$" allowed_country
Require env allowed_country

Article from the support category: PHP