Back to the knowledge base
Guide

Blocking Access from Selected Countries Using mod_geoip and .htaccess

Instructions and recommendations from the exon.io team.

Blocking Access from Selected Countries Using mod_geoip and .htaccess

The mod_geoip module allows you to restrict access to your website based on the visitor’s country. This can be useful when you want to block traffic from specific countries due to spam, unwanted bots, or security attacks.

Tip: The rules are added to the .htaccess file, which is usually located in the main website directory, for example in public_html.

Example of blocking selected countries

The example below blocks access from the listed countries:

<IfModule mod_geoip.c>

    RewriteEngine On

    RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^(CN|TR|BR|HK|PH|SG|VN|JP)$
    RewriteRule ^ - [F,L]

</IfModule>

What does this rule do?

The rule checks the GEOIP_COUNTRY_CODE variable, which contains the visitor’s two-letter country code. If the visitor’s country matches one of the listed codes, the server returns a 403 Forbidden response and access to the website is denied.

Country code Country
CNChina
TRTurkey
BRBrazil
HKHong Kong
PHPhilippines
SGSingapore
VNVietnam
JPJapan

How to change the list of blocked countries

You can adjust the list of countries by changing the country codes in this part of the rule:

^(CN|TR|BR|HK|PH|SG|VN|JP)$

For example, if you want to block only China and Russia, use:

<IfModule mod_geoip.c>

    RewriteEngine On

    RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^(CN|RU)$
    RewriteRule ^ - [F,L]

</IfModule>
Notice: Changes made in the .htaccess file take effect immediately after saving. We recommend editing these rules carefully to avoid accidentally blocking legitimate visitors.
Feedback

Was this answer helpful?

Your response helps us improve our guides.