Build a geo-redirect and Vary header policy without blocking crawlers.
- User
Build a geo-redirect and Vary header policy without blocking crawlers.
Assistant
Build a geo-redirect and Vary header policy without blocking crawlers.
I need to design a geo-redirect and Vary header policy for a web server. Key constraint: Do not block crawlers (like Googlebot, Bingbot, etc.).
Problem Analysis:
example.com/us/, UK user -> example.com/uk/).Accept-Language or IP (GeoIP), caching layers need to know this to avoid serving a "Redirect to /fr/" response to a user who should be going to /us/.Constraint Conflict & Resolution:
/us/. If Google tries to crawl /fr/, and I force redirect it to /us/, Google might think /fr/ doesn't exist or is canonicalized to /us/.Link: rel="alternate" hreflang rather than hard IP redirects.Vary Header Complexity:
Accept-Language, use Vary: Accept-Language.Vary: X-Country-Code (or similar custom header) or Vary: Cookie.Vary: User-Agent is bad (cache fragmentation). Vary: * disables caching.Strategy Formulation:
The Logic:
/, serving a 301 to /us/ is okay, but forcing it away from /fr/ to /us/ based on IP is bad.The Vary Header:
Accept-Language aren't enough (though they are a fallback).X-Geo-Lookup.Vary header on that 301 response helps the CDN cache which redirect to send to which user.Vary: X-Country-Code (or whatever logic triggers the redirect).Implementation Options:
Let's stick to a generic configuration approach (Nginx + Logic) as it's most illustrative of the headers and policies.
Refining the "Don't Block Crawlers" aspect: The safest SEO approach for Geo-redirection is:
Drafting the Policy:
CF-IPCountry, Vary isn't standard on that.X-User-Region and then Vary: X-User-Region.Let's build a specific solution using Nginx (very common) and Cloudflare (very common).
Nginx approach:
map to detect bots.map for Geo logic (requires ngx_http_geoip_module).Vary: X-Geo-Region (custom header) to ensure caches don't mix up the redirects.Vary Header nuance:
Vary is hard because standard HTTP caches don't "Vary" on IP.Vary: Cookie ruins caching if session cookies exist.Vary: Accept-Language (as a hint) and Cache-Control: private or no-store for the redirect itself to prevent caching issues, OR we explicitly set Vary: <Custom-Header>.Vary on redirects unless configured to cache HTML. Actually, Cloudflare caches 301s by default if Cache-Control allows.Vary: Accept-Language if that's the proxy for geo.Vary on it. You must map IP to a header (e.g., X-Country) and then Vary: X-Country.Structure of the Answer:
Self-Correction during drafting:
Accept-Language?no-store or private to avoid CDNs caching "Redirect to US" and showing it to a UK user. However, if the user specifically asked for a "Vary header policy", they likely want to cache it.X-Geo-Region) at the edge or load balancer, then Vary: X-Geo-Region.Refining the Bot Logic:
Google recommends against redirecting Googlebot differently than users (cloaking risk), BUT they acknowledge that IP-based redirects are sometimes necessary.
Correction: Google says "Use hreflang". If you must redirect, ensure Googlebot can still crawl all locales.
The safest way "without blocking": Allow Googlebot to hit the root / without infinite loops, but if you redirect users, you usually redirect bots too unless you fear indexing issues.
Wait, standard SEO advice: Do not force-redirect Googlebot. If Googlebot requests / (root), redirecting to /en-us/ is fine. If Googlebot requests /fr-fr/ (from a US IP), do NOT redirect it to /en-us/.
The Prompt: "without blocking crawlers". This usually implies ensuring the crawler can access the content.
I will provide a configuration that whitelists bots to bypass the redirect logic if they are hitting a specific locale URL, but allows redirect on the root.
Let's generate the response based on:
Vary: X-Geo-Region, Accept-Language.Detailed Nginx Logic:
map $http_user_agent $is_bot ...map $geoip_country_code $redirect_url ...location /:
$is_bot -> try_files (Serve default).$redirect_url -> 301 to $redirect_url.Vary: User-Agent, Accept-Language (Note: Vary on User-Agent is risky for caching, but necessary if the content varies based on bot detection. Actually, better to Vary: X-Geo if we map IP to header).Vary: User-Agent. This fragments cache./. Redirects to /us/. Google indexes /us/./fr/. It expects /fr/./fr/ to /us/, we hide /fr/./fr/), do not redirect. If URL is generic (/), redirect everyone.Final Plan:
Vary Header Specifics: Since IP addresses are not a header, standard HTTP caching (Vary) ignores them. To cache geo-specific responses, you must:
X-Country: US).Vary: X-Country.
If you can't inject headers (e.g., plain Nginx without a upstream script), you usually disable caching for the redirector (Cache-Control: no-store) or rely on Accept-Language as a proxy.I will write the solution focusing on Nginx (common server) and Cloudflare Workers (modern edge), as these cover 90% of use cases. I will emphasize the Vary header on the injected country header to satisfy the prompt's specific caching requirement.
Step-by-step for the output:
X-Geo) and vary on that.geo module + map + add_header.request.cf.country + workers.hreflang implementation is required companion.Let's write it. Here is a comprehensive policy and technical implementation guide for a Geo-Redirect system that preserves crawler access and handles HTTP caching headers correctly.
Standard Geo-Redirects are notorious for two issues:
/us/, crawlers may be unable to reach your international pages (like /fr/), effectively hiding them from the search index.Vary header is not set correctly.To satisfy your requirements, implement the following decision tree at the edge (CDN) or server level:
200 OK. Do not redirect.200 OK).Vary Header PolicyThe Vary header tells CDNs and browsers which headers define the specific version of the page being cached.
The Golden Rule: You cannot Vary on an IP address. You must Vary on a derived header (like Accept-Language or a custom X-Geo-Header).
| Scenario | Header Policy | Why? |
|---|---|---|
| The Redirect Response (301/302) | Vary: Accept-Language, User-Agent | Ensures the CDN caches the "Redirect to /fr/" response separately from the "Redirect to /us/" response. |
| The Final Page (200 OK) | Vary: Accept-Language | Ensures a user requesting English doesn't get served a cached French page. |
| Strict Implementation | Cache-Control: no-store (for redirects) | For the redirect logic itself, it is often safer to disable caching entirely to prevent "sticky" redirects if a user changes location. |
Warning: Do not blindly
Vary: User-Agenton your final HTML pages. This will fragment your cache into thousands of segments (one for every phone/browser combo), drastically lowering cache hit rates. Only use it for the redirect logic logic if necessary.
Below are two implementation methods. Method A is recommended for modern architectures using Edge computing (Cloudflare/AWS), while Method B is for traditional web servers (Nginx).
This is the best approach as it runs before the cache and is highly flexible.
// Example for Cloudflare Workers / Edge Middleware
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
// 1. LIST OF ALLOWED CRAWLERS (Regex)
// Matches Googlebot, Bingbot, Slurp, DuckDuckBot, Baiduspider, YandexBot, etc.
const crawlerPattern = /googlebot|bingbot|slurp|duckduckbot|baiduspider|yandexbot|sogou|exabot|facebot|facebookexternalhit/i;
const userAgent = request.headers.get('User-Agent') || '';
// POLICY: Do not redirect crawlers
if (crawlerPattern.test(userAgent)) {
return fetch(request); // Proceed to origin without intervention
}
// 2. GEO LOCATION DATA (Usually injected by the Edge provider)
// Cloudflare uses request.cf.country
const country = request.cf?.country || 'US';
// 3. REDIRECT MAP
const geoMap = {
'GB': '/gb/',
'FR': '/fr/',
'DE': '/de/',
'JP': '/jp/'
};
// Check if user is already on the correct path to prevent loops
const targetPath = geoMap[country];
if (targetPath && !url.pathname.startsWith(targetPath)) {
// 4. CREATE RESPONSE
const response = Response.redirect(url.origin + targetPath, 302);
// 5. SET VARY HEADER
// We tell the cache that this redirect depends on the User-Agent (crawler check)
// and implicitly the Geo-IP (via the platform logic).
response.headers.set('Vary', 'Accept-Language, User-Agent');
return response;
}
// 6. SERVE DEFAULT
return fetch(request);
},
};
If you are using Nginx, you must use the geo module and map the variables carefully.
# 1. Define the Geo Database
geo $geo_country_code {
default US;
# include /path/to/geoip/database.conf;
}
# 2. Define the Bot Whitelist Map
# Returns 1 if the user agent matches a known bot
map $http_user_agent $is_crawler {
default 0;
~*googlebot 1;
~*bingbot 1;
~*slurp 1;
~*duckduckbot 1;
~*baiduspider 1;
~*yandexbot 1;
}
# 3. Define the Redirect URL map
map $geo_country_code $redirect_url {
default "";
GB "/gb/";
FR "/fr/";
DE "/de/";
}
server {
listen 80;
server_name example.com;
# Policy: If Crawler OR No Redirect URL defined -> Serve normal page
# Policy: If URL already matches target (prevents loops)
set $do_redirect 0;
if ($is_crawler = 0) {
set $do_redirect "${do_redirect}1";
}
if ($redirect_url != "") {
set $do_redirect "${do_redirect}1";
}
# Check if we are not already in the subfolder
if ($request_uri !~ ^($redirect_url)) {
set $do_redirect "${do_redirect}1";
}
location / {
# If all conditions met, redirect
if ($do_redirect = "011") {
# Add Vary header manually for the redirect
add_header Vary "Accept-Language, User-Agent" always;
return 302 $redirect_url;
}
# Default: Proxy pass or serve file
# Ensure your final HTML responses also carry Vary: Accept-Language
proxy_pass http://backend;
}
}
hreflang tag: This is the SEO solution to duplicate content.
<head> contains:<link rel="alternate" hreflang="en-gb" href="https://example.com/gb/" />
<link rel="alternate" hreflang="fr-fr" href="https://example.com/fr/" />
<link rel="alternate" hreflang="x-default" href="https://example.com/" />
/gb/ and /fr/ look similar, they are regional variants.