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.
.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 |
|---|---|
CN | China |
TR | Turkey |
BR | Brazil |
HK | Hong Kong |
PH | Philippines |
SG | Singapore |
VN | Vietnam |
JP | Japan |
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>
.htaccess file take effect immediately after saving.
We recommend editing these rules carefully to avoid accidentally blocking legitimate visitors.
Was this answer helpful?
Your response helps us improve our guides.