Skip to content

How to Block a Country in nginx

Key idea:

Geo-blocking in nginx via ngx_http_geoip2_module + MaxMind GeoLite2 database. IP lookup → country code → allow/deny via map or if. Useful for compliance (GDPR, sanctions), reducing bot traffic. Cons: VPNs bypass easily, legitimate travellers get blocked, MaxMind requires signup (free tier fine).

Below: step-by-step, working examples, common pitfalls, FAQ.

Check your site's security →

Step-by-Step Setup

  1. Register a free MaxMind account → download GeoLite2-Country.mmdb
  2. Install the nginx module: apt install libnginx-mod-http-geoip2
  3. In nginx.conf http context: geoip2 /path/GeoLite2-Country.mmdb { $geoip_country_code country iso_code; }
  4. Map country → action: map $geoip_country_code $blocked { default 0; CN 1; RU 1; }
  5. In server block: if ($blocked) { return 403; }
  6. Auto-update GeoLite2 via geoipupdate daemon (monthly)
  7. Test: curl -H "X-Forwarded-For: 1.2.3.4" https://example.com

Working Examples

ScenarioConfig
Basic country blocking# nginx.conf http: geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb { $geoip_country_code country iso_code; } map $geoip_country_code $blocked { default 0; CN 1; KP 1; } # server: if ($blocked) { return 403; }
Whitelist only (allow some)map $geoip_country_code $allowed { default 0; US 1; CA 1; GB 1; DE 1; } if ($allowed = 0) { return 403; }
Custom blocked pagelocation = /blocked.html { internal; root /var/www/static; } if ($blocked) { error_page 403 /blocked.html; return 403; }
Allow admin IP bypassset $skip 0; if ($remote_addr = "1.2.3.4") { set $skip 1; } if ($blocked = 1) { set $skip "${skip}1"; } if ($skip = 1) { return 403; }
geoipupdate daemon# /etc/GeoIP.conf AccountID XXX LicenseKey YYY EditionIDs GeoLite2-Country # Cron: 0 3 1 * * /usr/bin/geoipupdate

Common Pitfalls

  • VPN + Tor bypass any geo-blocking easily
  • Legitimate travellers get blocked (business users on holiday)
  • Cloudflare in front of nginx → $remote_addr = Cloudflare IP, not client. Use $http_cf_ipcountry or real_ip_header
  • GeoLite2 accuracy is country-level 99%, city-level 70% — don't rely on city
  • Compliance: legal risk to block whole countries (discrimination). Consult legal

TL;DR: How to Block a Country in nginx

To block a country in nginx, you can use the geo directive along with map and the if directive to deny access based on IP address ranges. For example, to block traffic from the United States, you can include the following in your nginx configuration file:

geo $block_us { default 0; 192.0.0.0/8 1; }

Then, use this variable within a server block to deny access:

server { if ($block_us) { return 403; } }

Remember to replace the IP range with the specific ranges for the country you wish to block.

Understanding IP Geolocation for nginx

Blocking a specific country in nginx requires an understanding of IP geolocation. Each country is assigned a range of IP addresses, which can be utilized to filter out unwanted traffic. Services like IP2Location and DB-IP provide comprehensive databases that map IP address ranges to their respective countries.

For instance, as of 2026, the IP range for Germany includes 5.0.0.0/8, 62.0.0.0/8, and many others. By using these ranges, you can effectively block access to your web server from Germany or any other country.

How to Obtain IP Ranges

To block a country, you first need to gather the IP address ranges associated with that country. Here’s a simple process:

  1. Visit an IP geolocation database provider.
  2. Download the CSV or text file containing the IP ranges.
  3. Extract the relevant ranges for your target country.

For example, if you want to block traffic from France, you would obtain the IP ranges for France from a database like IP2Location.

Implementing the Configuration in nginx

Once you have the IP ranges, you can implement them in your nginx configuration. Here’s an example of how to block traffic from France:

geo $block_fr { default 0; 80.10.0.0/16 1; 90.0.0.0/8 1; 195.0.0.0/8 1; }

In this example, the geo directive creates a variable $block_fr that is set to 1 for any IP address that matches the specified ranges.

Using the Variable in Your Server Block

After defining the geo variable, you need to incorporate it into your server block to deny access:

server { listen 80; server_name example.com; if ($block_fr) { return 403; } }

This configuration will return a 403 Forbidden status code to any request coming from the specified IP ranges associated with France.

Testing Your Configuration

Before deploying your changes to a production environment, it’s crucial to test your nginx configuration for syntax errors:

nginx -t

If the test is successful, you can then reload nginx to apply the changes:

systemctl reload nginx

It’s advisable to monitor your server logs after implementing these changes to ensure that legitimate users aren’t being inadvertently blocked. Use tools like tail -f /var/log/nginx/access.log to track incoming requests and verify their origins.

Considerations When Blocking Countries

While blocking countries can reduce unwanted traffic, it’s important to consider the implications:

  • Legitimate Users: You may inadvertently block legitimate users, including those using VPNs or proxies.
  • SEO Impact: Blocking access from certain countries might affect your site's SEO, especially if you have a global audience.
  • Maintenance: IP address ranges change over time, so regular updates to your configuration may be necessary.

To mitigate these issues, consider implementing a more nuanced approach, such as rate limiting or using a web application firewall (WAF) to handle unwanted traffic more intelligently.

HeadersCSP, HSTS, X-Frame-Options, etc.
SSL/TLSEncryption and certificate
ConfigurationServer settings and leaks
Grade A-FOverall security score

Why teams trust us

OWASP
guidelines
15+
security headers
<2s
result
A–F
security grade

How it works

1

Enter site URL

2

Security headers analyzed

3

Get grade A–F

What Does the Security Analysis Check?

The tool checks HTTP security headers, SSL/TLS configuration, server info leaks, and protection against common attacks (XSS, clickjacking, MIME sniffing). A grade fromA to F shows overall security level.

Header Analysis

Checking Content-Security-Policy, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, and more.

SSL Check

TLS version, certificate expiry, chain of trust, HSTS support.

Leak Detection

Finding exposed server versions, debug modes, open configs, and directories.

Report with Recommendations

Detailed report explaining each issue with specific steps to fix it.

Who uses this

Security teams

HTTP header audit

DevOps

config verification

Developers

CSP & HSTS setup

Auditors

compliance checks

Common Mistakes

Missing Content-Security-PolicyCSP is the primary XSS defense. Without it, script injection is much easier.
Missing HSTS headerWithout HSTS, HTTPS-to-HTTP downgrade attacks are possible. Enable Strict-Transport-Security.
Server header exposes versionServer: Apache/2.4.52 helps attackers find exploits. Hide the version.
X-Frame-Options not setSite can be embedded in iframe for clickjacking. Set DENY or SAMEORIGIN.
Missing X-Content-Type-OptionsWithout nosniff, browsers may misinterpret file types (MIME sniffing).

Best Practices

Start with basic headersMinimum: HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy. Takes 5 minutes.
Implement CSP graduallyStart with Content-Security-Policy-Report-Only, monitor violations, then enforce.
Hide server headersRemove Server, X-Powered-By, X-AspNet-Version from responses.
Configure Permissions-PolicyRestrict camera, microphone, geolocation access — only what is actually used.
Check after every deploySecurity headers can be overwritten during server configuration updates.

Get more with a free account

Security check history and HTTP security header monitoring.

Sign up free

Learn more

Frequently Asked Questions

Cloudflare geo-blocking vs nginx?

Cloudflare: simple dashboard toggle, blocks before origin. nginx: more flexible, no CDN dependency. For critical security — both.

MaxMind vs IP2Location?

MaxMind GeoLite2 — free, good accuracy, standard. IP2Location — commercial, more details (proxy/VPN detection).

How to unblock admin from a blocked country?

Whitelist their IP BEFORE the country check. Or a separate admin.example.com without geo-block.

Which countries get blocked most?

Sanctions compliance: CU, IR, KP, SY. Security: countries with high bot activity. Business: where you have no support.

Try the live tool that powered this guide

Free plan — 10 monitors, checks every 5 min, no card required. Upgrade for 1-minute interval and multi-region monitoring.