Support > About independent server > Introduction to the method of blocking all access IP addresses from specified countries
Introduction to the method of blocking all access IP addresses from specified countries
Time : 2025-05-14 11:29:42
Edit : Jtti

Due to data compliance, network security or special business strategy requirements, enterprises may need to block IP access from specific countries. How to block a specific access IP? This article will share with you the full-process implementation plan from obtaining from the IP library to real-time interception, including firewall configuration, web server rules, CDN policies, and automated maintenance methods, etc.

The first step is the selection and acquisition of the IP geographical location database. MaxMind GeoLite2 is a widely used free database that provides the mapping relationship between countries and ips. Installation steps:

wget https://geolite.maxmind.com/download/geoip/database/GeoLite2Country.tar.gz
tar zxvf GeoLite2Country.tar.gz
mv GeoLite2Country_/GeoLite2Country.mmdb /usr/local/share/GeoIP/

The commercial version of GeoIP2 has higher accuracy and supports hourly updates. Enterprise-level users can obtain real-time data through API:

The curl s "https://api.maxmind.com/geoip/v2.1/country/1.1.1.1?pretty" \
u "USER_ID:LICENSE_KEY"

The Regional Internet Registry (RIR) provides original IP allocation data, which is suitable for scenarios that require self-maintenance of checklists. For example, the daily data of APNIC:

wget ftp://ftp.apnic.net/pub/stats/apnic/delegatedapniclatest
grep '|CN|ipv4' delegatedapniclatest | awk F'|' '{print $4 "/" 32log($5)/log(2)}' > cn_ips.txt

The firewall layer intercepts the batch addition of rules using iptables (taking the blocking of Chinese IP as an example) :

# Create an IP collection
ipset create cn_ips hash:net
# Import the IP segment
while read line;  do
ipset add cn_ips $line
done < cn_ips.txt
# Set firewall rules
iptables I INPUT m set matchset cn_ips src j DROP
iptables I FORWARD m set matchset cn_ips src j DROP

The nftables solution has better performance:

table inet filter {
set cn_ips {
type ipv4_addr
flags interval
elements = {1.0.1.0/24, 1.0.2.0/23,... }
}
chain input {
type filter hook input priority 0;
ip saddr @cn_ips drop
}
}

Key parameter optimization

hashsize is adjusted according to the number of ips (default 1024).

maxelem sets a sufficiently large capacity (such as 1,000,000)

timeout Dynamic IP Expiration Time (Suggested 86,400 seconds)

Web server-level interception Nginx configuration example (ngx_http_geoip_module needs to be installed) :

http {
geoip_country /usr/local/share/GeoIP/GeoLite2Country.mmdb;
map $geoip_country_code $block_country {
default 0;
CN 1;
RU 1;
}
server {
if ($block_country) {
return 403;
}
}
}

The Apache solution uses mod_geoip:

GeoIPEnable On
GeoIPDBFile /usr/local/share/GeoIP/GeoIP.dat
RewriteEngine On
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^(CN|RU)$
RewriteRule ^(.) $  [F]

Performance impact test: On a 4-core server, after enabling GeoIP detection, the QPS dropped from 12,000 to 10,500, requiring a 10% increase in hardware redundancy.

Configuration steps for Cloudflare's CDN and cloud platform solution:

Add the expression: (ip.geoip.country eq "CN") in the firewall rules. Operation select "Block" to set the effective range (full site or specific path), geographic matching rules such as creating Web ACLs, adding geographic matching conditions (Country codes: CN), associated ALB or CloudFront distributions, and updated the IP list daily using crontab:

0 3    /usr/bin/curl s  https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2Country&license_key=YOUR_KEY&suffix=tar.gz o  GeoLite2Country.tar.gz && tar xzf GeoLite2Country.tar.gz stripcomponents=1 C /usr/local/share/GeoIP/ && systemctl reload  nginx

The response strategy for bypassing detection can detect common ports (such as 1194) :

iptables A INPUT p tcp dport 1194 j DROP
iptables A INPUT p udp dport 1194 j DROP

Deep Packet Inspection (DPI) identifies protocol characteristics:

nft add rule inet filter input tcp dport 443 tcp payload @ 0,16 1352148815254781952 drop

Use IP reputation databases (such as AbuseIPDB) :

curl s https://api.abuseipdb.com/api/v2/check \
dataurlencode "ipAddress=1.1.1.1" \
H "Key: YOUR_API_KEY" \
H "Accept: application/json"

Check the isTor or abuseConfidenceScore field in the response.

Behavioral pattern analysis configures Fail2ban rules to identify abnormal access:

[geoblock]
enabled = true
filter = geoblock
action = iptablesallports[name=GeoBlock]
logpath = /var/log/nginx/access.log
maxretry = 5
findtime = 600

Custom filter

# /etc/fail2ban/filter.d/geoblock.conf
[Definition]
failregex = ^<HOST>."GET \/admin.

Performance optimization and testing can use the stress testing tool vegeta to verify the interception efficiency:

echo "GET http://target.com" | vegeta attack duration=60s rate=1000 | tee results.bin | vegeta report

The key indicators include an interception accuracy rate of over 99.99%, a false blocking rate of less than 0.001%, and a delay growth of no more than 5ms after the addition of new rules

Hardware-level acceleration solutions include using DPDK to enhance network throughput, deploying intelligent network cards to execute filtering rules, and achieving rapid judgment at the kernel layer based on eBPF. In terms of legal compliance and privacy protection, EU users are required to clearly inform the geographical blockade policy in GDPR compliance. Data retention access logs should be kept for no more than 30 days. The exemption mechanism should set up an appeal channel to handle accidental blocking situations. The history of changes in audit record retention rules should be at least 180 days. When implementing geographic blocking, a statement should be added at the bottom of the website

Through the above multi-level protection system, access to designated country IP addresses can be effectively blocked, while ensuring the stable operation of business systems. It is recommended to conduct a rule audit every quarter and adjust the strategy in combination with business development. Today, with the coexistence of globalization and localization demands, intelligent geographic access control has become an indispensable component of enterprise security architectures.

 

Relevant contents

In which scenarios are the E5 and E3 servers respectively applicable? And analysis of specific architectural differences What are the benefits of the collaboration between video storage servers and CDN High-bandwidth servers are known as the core engine driving the digital age Deep Challenges and Solutions for Overseas High-defense Server Cores and IO Systems When testing a server, is it better to set the TTL parameter value as low as possible? How about choosing a US data center for a high-bandwidth server? Is it better to use SSD or HDD for a large hard disk server? What should I consider when renting a Hong Kong BGP multi-line server? What is a single-channel video server configuration and how to choose it What is the difference between Hong Kong dedicated servers and US servers?
Go back

24/7/365 support.We work when you work

Support