You can geo-block a website by country and keep it crawlable, if you enforce the restriction where it actually applies. When the rule covers checkout or signup, block the order or the account, not the product page. Googlebot should see what a visitor from the same country sees, and that cuts both ways: a public page that keeps answering 403 or 451 can still fall out of Google's index.
This post covers how to decide between blocking, challenging, and suggesting, where to enforce it (CDN, web server, or app), how a VPN can undo a legal block, and when to fail open. It ends with a short Express middleware that gates only the actions that need it and refuses to guess when its data is incomplete.
TL;DR
- Decide first: a legal demand gets a block, a licensing limit gets a refusal, regional abuse gets a challenge, and wrong-storefront visitors get a suggestion banner, not a redirect.
- Googlebot's default crawler addresses are in the US, and Google says to treat it like any visitor from the same country. A public page that keeps returning 4xx to those crawls can drop out of the index.
- Block the action, not the page. Gate the POST that creates the account or places the order; keep product pages, docs, and blog posts open wherever the rules allow.
- Use 451 when a legal demand is the reason, 403 for other refusals, and
Cache-Control: no-store on both. Never answer a blocked visitor with a 200 "not available" page.
- A country lookup sees the VPN's exit country, not the person's. If a legal rule is behind the block, ask whoever owns compliance whether anonymizer screening is expected; OFAC suggests it to virtual currency companies.
Short version: geo-blocking costs you rankings when it changes what crawlers can fetch on public pages. Keep those pages open wherever you can, gate the restricted actions behind honest status codes, and make the middleware fail closed instead of guessing.
"Geo-block" gets used for four different jobs, and each one wants a different response:
| Why you're restricting | What to do | Status code |
| Legal demand: sanctions, a court order, gambling law | Block the restricted action | 451 |
| Contract: a license that covers some territories only | Refuse the restricted action or content | 403 |
| Abuse concentrated in one region | Challenge (CAPTCHA) or rate-limit | 429 for a rate limit, 403 after a failed challenge |
| Visitor is on the wrong storefront or language | Suggest the right version with a banner | 200 |
The last row is the one people most often build as a block or a forced redirect, and it's the one that hurts most. A banner that says "Looks like you're in Canada. Go to the Canadian store?" keeps every URL reachable for people and crawlers, and hreflang tags tell search engines which version belongs to which market. A forced redirect hides every version but one.
The abuse row is usually better handled at your CDN than in your app, and a challenge beats a block because the person on the other end of a shared mobile IP may be a customer. Keep rate limits off public pages where you can: Google treats a 429 like a server error and slows its crawl.
The first two rows are the real geo-blocks, and the rest of this post is mostly about doing them without collateral damage. RFC 7725 defines 451 for access denied "as a consequence of a legal demand," which is why a private licensing limit gets a 403 instead.
Why Googlebot's location matters
Two facts from Google's own docs drive everything else.
First, Googlebot mostly crawls from the US. Google's page on how it crawls locale-adaptive pages says the default crawler addresses "appear to be based in the USA" and that requests go out without an Accept-Language header. It also crawls from other countries, and the instruction for those crawls is blunt: "treat it like you would treat any other user from that country."
Second, Google drops pages that return client errors. Its HTTP status code documentation says "Google doesn't index URLs that return a 4xx status code, and URLs that are already indexed and return a 4xx status code are removed from the index."
Put those together. Block the US on public pages, or run an allowlist that leaves the US out, and every crawl from Google's default addresses gets a 4xx; URLs that keep returning it drop out of the index. Blocking other countries touches fewer of Google's crawls, but not none: Google does crawl from other countries, and those crawls get the same 4xx a local visitor gets. How Google weighs a URL that answers 200 in one country and 451 in another isn't documented, so don't build on a guess. Keep public pages out of the block wherever the rules let you.
The tempting fix is to allowlist Googlebot by user agent. Don't. Google's instruction is to treat its crawler like a local visitor, and a user-agent check also lets anyone in who types "Googlebot" into curl. If you need to recognize Google's crawlers for rate limits, verify them: a reverse DNS lookup on the address should return a hostname under googlebot.com, google.com, or googleusercontent.com, and a forward lookup on that hostname should return the same address. Then rate-limit them, but serve them the same content.
Block the action, not the page
Here's the position I'd defend in any architecture review: most geo-blocks should guard an action, not a page.
When the restriction is legal, the restricted thing is often a transaction: creating an account, placing an order, downloading a licensed file. Gate those routes and leave the catalog, the docs, and the blog open. Every crawler, from every country, gets the same 200 pages, so there's nothing for the index to lose. A Google crawl from a restricted country still sees your product pages, because the block lives on POST /checkout, the request that places an order. That's a route design decision, not a bet on crawler behavior: crawlers can send POST requests too, but an order endpoint isn't a page you need indexed. The same goes for forms: gate POST /signup, the request that creates the account, not GET /signup, the page that shows the form.
Sometimes the content itself is restricted, such as video licensed for one market. Then refuse the page itself: 451 if a legal demand is the reason, 403 if it's a license. Expect the page to lose search visibility, and don't assume the loss stays inside the blocked country. That's the restriction working, not a bug to engineer around. Send Cache-Control: no-store with the refusal, too: a 451 is cacheable by default, and a shared cache could serve one visitor's refusal to everyone.
What you should never do is answer a blocked visitor with a 200 and a "not available in your region" message. To a crawler from that country, that message is your page.
Where to geo-block by country: CDN, server, or app
| Layer | Good for | Watch out for |
| CDN or WAF (Cloudflare custom rules) | Whole-site or path blocks before traffic reaches you | Default block status is 403; a custom status like 451 needs Pro or above |
| Web server (Nginx) | Path rules without touching app code | You ship and update the database file yourself |
| Application middleware | Per-action rules, VPN checks, fail-open or fail-closed per route | Adds a lookup to the request path, so cache it |
On Cloudflare, country blocking runs through WAF custom rules on every plan (the older IP Access rules only block by country on Enterprise). Use the ip.src.country field; ip.geoip.country is deprecated. Scoped to the restricted actions (POST only, so the signup form itself still loads), with your own country list in place of the example, the rule expression looks like this:
(http.request.method eq "POST" and http.request.uri.path in {"/signup" "/checkout"} and ip.src.country in {"KP"})
On Nginx, the built-in ngx_http_geoip_module has read MMDB files since 1.31.7 (October 2026). On older versions, the third-party ngx_http_geoip2_module does the same job. Either way, map the country to a variable and return 451 on the restricted locations.
Edge rules are the cheapest way to block IPs by country, but on most plans they only know the country. Cloudflare's managed VPN and anonymizer lists work in custom rules on Enterprise plans only; everywhere else, the edge can't tell you an address is a VPN, which matters more than people expect.
The VPN gap when the block is legal
A country lookup tells you where an address is registered and routed, not where the person is. RFC 7725, the spec that created HTTP 451, says it outright: "clients can still access the denied resource by using technical countermeasures such as a VPN or the Tor network."
For an abuse block, that's fine. For a legal one, it's a known gap. OFAC's sanctions guidance for the virtual currency industry, for example, tells companies to use geolocation and IP blocking, and gives screening addresses "against known virtual private network (VPN) IP addresses" as one way to catch misattributed IPs. That's guidance for one industry, not a universal rule, so ask whoever owns compliance what your regime expects.
If the answer is yes, two practical rules follow. Check for VPNs, proxies, and Tor on the restricted action. And check at the action itself, every time, not once at signup: a customer who signed up from home can place an order from anywhere.
Fail open or fail closed
Every lookup can fail: a timeout, an outage, a quota you forgot to raise. Decide per route what happens then.
For a legal block, fail closed on the restricted action. That includes the quiet failure: a lookup that answers but leaves out the country or a flag. A 503 with Retry-After tells a real customer to try again in a moment, and it costs nothing in search, because the checkout endpoint isn't a page that needs to be indexed. The trade-off is real: while the lookup is down, every order waits with it.
For rules nothing obliges you to enforce first, such as throttling a region that sends spam signups, fail open. Turning a lookup outage into a site outage is a bad trade. A license or contract that requires the check before delivery belongs with the legal blocks, not here.
And never put a fail-closed lookup in front of your pages. Google's crawlers slow down when they see 5xx errors, and Google says URLs that keep returning them are "eventually dropped" from the index. A lookup provider's bad hour shouldn't become your bad month in search.
A short Express middleware
The example uses ipgeolocation.io's IP Geolocation API, because one call returns the country plus VPN, proxy, and Tor flags. The security flags need a key with security access. For a country-only rule, set GEO_CHECK_ANONYMIZERS=false: the gate skips the security module and the VPN check, and the country alone decides. Don't just delete include=security from the URL, because this code treats a missing flag as unknown, never as a pass.
// geo-gate.js: block restricted actions (not whole pages) by country. Node 18+.
const API = 'https://api.ipgeolocation.io/v3/ipgeo';
const FLAGS = ['is_vpn', 'is_proxy', 'is_tor']; // relays keep the user's region, so they're not here
const CHECK_ANONYMIZERS = process.env.GEO_CHECK_ANONYMIZERS !== 'false'; // 'false' = country only
const isCountry = (c) => /^[A-Z]{2}$/.test(c) && c !== 'XX' && c !== 'ZZ'; // XX and ZZ mean "unknown"
// Your compliance owner supplies this list. There's deliberately no default.
const RESTRICTED = new Set((process.env.GEO_RESTRICTED || '').split(',')
.map((c) => c.trim().toUpperCase()).filter(Boolean));
if (RESTRICTED.size === 0 || ![...RESTRICTED].every(isCountry)) {
throw new Error('Set GEO_RESTRICTED to ISO country codes, for example GEO_RESTRICTED=KP');
}
const TTL_MS = 60 * 60 * 1000;
const cache = new Map(); // swap for Redis when you run more than one instance
async function lookup(ip) {
const hit = cache.get(ip);
if (hit && Date.now() - hit.at < TTL_MS) return hit.geo;
const fields = ['location.country_code2', ...(CHECK_ANONYMIZERS ? FLAGS.map((f) => `security.${f}`) : [])];
const url = `${API}?apiKey=${encodeURIComponent(process.env.IPGEO_API_KEY)}` +
`&ip=${encodeURIComponent(ip)}${CHECK_ANONYMIZERS ? '&include=security' : ''}&fields=${fields.join(',')}`;
const res = await fetch(url, { signal: AbortSignal.timeout(1500) });
if (!res.ok) throw new Error(`lookup failed with HTTP ${res.status}`);
const data = await res.json();
const code = String(data?.location?.country_code2 ?? '').trim().toUpperCase();
const flags = FLAGS.map((f) => data?.security?.[f]);
const geo = {
country: isCountry(code) ? code : null,
// null means unknown: a missing flag must never read as "not a VPN".
hidden: !CHECK_ANONYMIZERS ? false
: flags.every((v) => typeof v === 'boolean') ? flags.some(Boolean) : null,
};
// Cache complete answers only, so a partial response can't stick for an hour.
if (geo.country && geo.hidden !== null) {
if (cache.size > 50_000) cache.clear(); // crude cap so a scan can't eat your memory
cache.set(ip, { at: Date.now(), geo });
}
return geo;
}
// Every answer depends on the visitor's IP, so shared caches must never store one.
function deny(res, status, message) {
return res.status(status).set('Cache-Control', 'no-store').send(message);
}
function geoGate() {
return async (req, res, next) => {
let geo;
try {
geo = await lookup(req.ip);
} catch (err) {
console.error(`geo lookup failed: ${err.name}`); // never the URL: it carries the key
return deny(res.set('Retry-After', '30'), 503, 'Please try again in a moment.');
}
if (geo.country && RESTRICTED.has(geo.country)) {
res.set('Link', '<https://example.com/>; rel="blocked-by"'); // you are the blocker
return deny(res, 451, 'This service is not available in your country for legal reasons.');
}
// A legal gate doesn't guess: an unknown country or flag means "not decided yet".
if (!geo.country || geo.hidden === null) {
return deny(res.set('Retry-After', '30'), 503, 'Please try again in a moment.');
}
if (geo.hidden) return deny(res, 403, 'Turn off your VPN or proxy to complete this step.');
return next();
};
}
module.exports = { geoGate, lookup, cache };
Three decisions in there matter most. Anything the gate can't trust counts as unknown: a missing flag, a missing country, or a country that isn't a real two-letter code (XX and ZZ are common placeholders for "unknown"). Unknown means 503, not a pass, and only complete answers go in the cache. A restricted country gets its 451 before the VPN check runs, so a VPN exit in a restricted country is refused for the legal reason. And there's no default country list: the module refuses to start without GEO_RESTRICTED, uppercases what you give it, and rejects anything that isn't a country code, because a gate with a typo in its list blocks nobody and still looks fine in testing.
The rest is plumbing. Every refusal carries Cache-Control: no-store, since the answer depends on the visitor's IP. The 1,500 ms timeout keeps a slow lookup from hanging a checkout. The cache keeps repeat visitors from costing a lookup per request; in production, use Redis or similar so every instance shares it. The error log prints err.name and nothing else: the request URL carries the API key, and logging whole error objects is how keys end up in log files. Relays don't trip the VPN rule, since an iCloud Private Relay address stays in the user's own region.
Wiring it up, gated route by route:
const express = require('express');
const { geoGate } = require('./geo-gate');
const app = express();
// Leave TRUST_PROXY unset when Node faces the internet directly; Express then ignores
// X-Forwarded-For, so a visitor can't pick their own IP. Behind a CDN or load balancer,
// list exactly the proxies you run, e.g. TRUST_PROXY=loopback or TRUST_PROXY=10.0.0.0/8.
if (process.env.TRUST_PROXY) {
app.set('trust proxy', process.env.TRUST_PROXY.split(',').map((s) => s.trim()));
}
// Pages stay open to everyone, crawlers included. Only the restricted actions are gated.
app.get('/', (req, res) => res.send('Catalog'));
app.get('/signup', (req, res) => res.send('Signup form'));
app.post('/signup', geoGate(), (req, res) => res.send('Account created'));
app.post('/checkout', geoGate(), (req, res) => res.send('Order placed'));
if (require.main === module) app.listen(3000);
module.exports = app;
Leave TRUST_PROXY unset when Node faces the internet directly. Express's default then ignores X-Forwarded-For, and that matters: trust the header on a direct connection and a visitor can write any address into it and pick their own country. Behind a CDN or load balancer, list exactly the proxies you run. Trust too little and every visitor geolocates to your own data center.
I tested this offline against a stubbed fetch on Express 4.22.3 and 5.3.0, 15 cases in all: the 451 and its Link header (including a VPN exit in a restricted country, a response with no flags, and a lowercase country code), the 403s for VPN, proxy, and Tor in an allowed country, 503 when the lookup fails or returns a missing, blank, or placeholder country (with nothing cached), a malformed country list that stops the app from starting, country-only mode, a spoofed X-Forwarded-For ignored on a direct connection, no-store on every refusal, relays passing, and no lookup at all on GET / or GET /signup. To test your own version, replace the global fetch with a stub and send requests through node:http, so the stub never sees your test traffic.
Test it before you trust it
- From a connection in an allowed country,
POST /checkout should return 200, and every page should too, including GET /signup.
- From a VPN exit in a restricted country, the same POST should return 451, because the country check runs first. From a VPN exit in an allowed country, it should return 403.
- Point your stub at a response with no country, or with
ZZ, and confirm a 503, not a 200.
- On a direct connection, send a request with a fake
X-Forwarded-For and confirm the gate looked up your real address, not the header's.
- Check that every refusal carries
Cache-Control: no-store and that your CDN isn't caching it.
- After you ship, run a live test in Search Console's URL Inspection tool on your homepage and two or three key pages. You want 200s.
- Watch Search Console's crawl stats for a week. A jump in 4xx or 5xx responses means a rule is catching more than you meant.
If you take one thing from this: put the block on the action, give it an honest status code, and let crawlers see what local visitors see. Get those right and geo-blocking stays a compliance feature instead of an SEO incident.