Redirect Visitors by Country: The Complete 2026 Guide
Every method for redirecting website visitors by country compared: edge-side, server-side, client-side, and no-code. Includes code examples, SEO rules, platform-specific guides, and common mistakes to avoid.

You have international traffic, and you want visitors from different countries to land on different pages. Maybe it's a localized storefront, a language-specific landing page, or a region-restricted product catalog. The concept is simple: detect where someone is and send them to the right place. The execution? That's where most teams get tripped up.
This guide walks through every practical approach to redirecting visitors by country in 2026 — from quick no-code solutions to custom server-side implementations — with real code examples, SEO considerations, and the mistakes that silently break your international strategy.
Why redirect visitors by country?
Before diving into the how, let's ground the why with data. International traffic is not a niche concern: according to Statista, over 60% of all web traffic in 2025 came from outside the United States. If your site serves a global audience, a one-size-fits-all experience leaves money on the table.
The business case is straightforward:
- Higher conversion rates: A study by CSA Research found that 76% of online shoppers prefer to buy products with information in their own language. Redirecting to a localized page directly addresses this.
- Regulatory compliance: GDPR in Europe, LGPD in Brazil, POPIA in South Africa — different regions have different legal requirements. Country-based redirects can route visitors to compliant versions of your site.
- Localized pricing: Showing prices in local currency with purchasing power parity adjustments can increase non-US revenue by 15-30%, according to data from Paddle's 2024 pricing report.
- Better user experience: Nobody wants to land on a page in a language they don't speak or see shipping options that don't apply to their country.
“Localization is not a luxury — it's the baseline expectation of a global internet user. The brands that treat it as an afterthought are the ones losing international market share.”
How country detection works
Every method for redirecting by country starts with the same fundamental step: figuring out where the visitor is. The standard approach is IP geolocation — mapping the visitor's IP address to a geographic location using a database like MaxMind GeoLite2 or the geolocation data built into CDNs like Cloudflare.
Country-level IP geolocation is extremely reliable. MaxMind reports 99.5% accuracy at the country level for their GeoIP2 database. State-level accuracy drops to 80-90%, and city-level to 70-80%, but for country-based redirects, accuracy is essentially a solved problem. You can test how your own IP resolves with our free IP geolocation lookup tool.
There are three places where this detection can happen, and the choice matters more than most people realize:
Approach 1: Edge-side redirects (recommended)
Edge computing changed the game for geo-targeting. Instead of waiting for a request to travel to your origin server, edge workers run in data centers distributed across the globe — often within 50 milliseconds of the visitor. CDN providers like Cloudflare, Vercel, and AWS CloudFront include the visitor's country as a free header on every request.
Here's a Cloudflare Worker that redirects visitors by country:
// Cloudflare Worker — geo redirect by country
export default {
async fetch(request) {
const country = request.cf?.country; // "US", "DE", "JP", etc.
const url = new URL(request.url);
// Only redirect on the root path
if (url.pathname === '/') {
const countryRoutes = {
DE: '/de/',
FR: '/fr/',
JP: '/ja/',
BR: '/pt-br/',
};
const destination = countryRoutes[country];
if (destination) {
return Response.redirect(
url.origin + destination, 302 // Always 302 for geo redirects
);
}
}
return fetch(request);
}
};And the equivalent in Vercel Edge Middleware (for Next.js sites):
// middleware.ts — Next.js Edge Middleware
import { NextRequest, NextResponse } from 'next/server';
export function middleware(request: NextRequest) {
const country = request.geo?.country; // Built-in with Vercel
if (request.nextUrl.pathname === '/') {
const routes: Record<string, string> = {
DE: '/de',
FR: '/fr',
JP: '/ja',
BR: '/pt-br',
};
const destination = routes[country ?? ''];
if (destination) {
return NextResponse.redirect(
new URL(destination, request.url),
302
);
}
}
return NextResponse.next();
}Why edge is best: The redirect happens before your page even starts loading. There's no flicker, no external API call, and the geolocation data is free — it's included with the CDN. The visitor sees only the destination page, as if the original URL never existed.
Approach 2: Server-side redirects
If you run your own server (Node.js, PHP, Python, Ruby), you can resolve the visitor's IP against a geolocation database and return a 302 redirect. Here's an Express.js example using MaxMind's GeoLite2:
const maxmind = require('maxmind');
const path = require('path');
// Load the database once at startup
const dbPath = path.resolve('./GeoLite2-Country.mmdb');
const lookup = await maxmind.open(dbPath);
app.use((req, res, next) => {
const ip = req.headers['x-forwarded-for'] || req.ip;
const result = lookup.get(ip);
const country = result?.country?.iso_code;
const routes = { FR: '/fr/', DE: '/de/', JP: '/ja/' };
if (routes[country] && req.path === '/') {
return res.redirect(302, routes[country]);
}
next();
});Pros: Full control. No third-party dependency at runtime. Works with any backend framework.
Cons: You need to host and update the MaxMind database yourself (it updates weekly). All requests must reach your origin server, which adds latency for geographically distant visitors. Doesn't work on static sites or platforms like Shopify.
Approach 3: Client-side JavaScript (not recommended)
A JavaScript snippet on your page calls a geolocation API, gets the visitor's country, and redirects via window.location:
// Client-side geo redirect (NOT recommended)
fetch('https://ipapi.co/json/')
.then(res => res.json())
.then(data => {
if (data.country_code === 'DE') {
window.location.href = '/de/';
}
})
.catch(() => {
// Silently fail — visitor stays on default page
});This approach has serious problems:
- Page flicker: The original page loads completely, then the redirect fires. Visitors see a flash of the wrong page before being sent to the right one.
- Ad blocker interference: Popular ad blockers and privacy tools block requests to geolocation APIs, causing the redirect to silently fail for a significant percentage of visitors.
- SEO invisibility: Search engine crawlers typically do not execute JavaScript redirects. Google Search Central explicitly warns against client-side location-based redirects because they resemble cloaking.
- API rate limits: Free geolocation APIs impose request limits. At scale, you'll either hit caps or pay for every lookup.
Approach 4: No-code with GeoSwap (easiest)
If you want country-based redirects without writing or maintaining code, GeoSwap's GeoRedirect gives you a visual dashboard for creating redirect rules. Add a single script tag to your site, define rules like “visitors from Germany go to /de/”, and publish. The redirects execute at the edge using Cloudflare Workers under the hood.
What makes this different from other geo-targeting tools:
- Completely free: No pageview caps, no premium tiers, no credit card. Geo-targeting is a commodity — here's why we don't charge for it.
- SEO-safe by default: All redirects are 302s. Search engine and AI crawlers are automatically bypassed. Exclusion rules trigger a warning before you can publish.
- Works on any platform: Shopify, WordPress, Webflow, custom sites — anywhere you can add a script tag.
- No flicker: Edge execution means the redirect happens before the page renders.
Critical SEO rules for country redirects
Geo redirects and SEO have a complicated relationship. Follow these rules to keep your search rankings intact:
1. Always use 302 redirects
A 301 redirect tells search engines the move is permanent. A geo redirect is conditional — different visitors see different destinations. Using 301s can cause Google to de-index your original URL in favor of the redirect target. Always use 302 (temporary) for geo-based routing.
2. Use explicit rules, never exclusion rules
“Redirect visitors FROM France to /fr/” is safe. “Redirect everyone NOT in the US” is dangerous. Googlebot's IP addresses don't reliably resolve to any specific country, so exclusion rules can accidentally redirect the crawler away from your primary content.
3. Implement hreflang tags
Hreflang tags tell search engines which version of a page to show in which country's search results. They complement geo redirects: hreflang handles the search engine side, geo redirects handle the visitor side. Most multi-region sites need both. Use our free hreflang generator to create the correct tags.
4. Handle bots transparently
Search engine crawlers (Googlebot, Bingbot) and AI crawlers (GPTBot, ClaudeBot, PerplexityBot) should bypass geo redirect rules entirely. Let them see your default content. This is not cloaking — it's allowing crawlers to index all versions of your site. Use our bot checker to verify how crawlers experience your site.
Common mistakes and how to avoid them
After helping thousands of sites implement country-based redirects, these are the patterns that cause the most problems:
- Redirect loops: Page A redirects French visitors to Page B, but Page B also has a redirect rule that sends them back to Page A. Always test your rules from every targeted country.
- No fallback: What happens to visitors from a country you haven't configured? Without a default behavior, they may see an error or get stuck. Always have a fallback that serves your primary content.
- Forgetting mobile: Mobile users on cellular networks may resolve to different locations than WiFi users. VPN usage is also significantly higher on mobile. Test your redirects on both connection types.
- No override mechanism: A German expat living in Japan should be able to switch to the German version manually. Always provide a language/region selector that overrides the automatic redirect, typically using a cookie.
- Redirect chains: Visitor hits a marketing URL, which 301s to the homepage, which then geo-redirects to /de/. Each hop adds latency and confuses search engines. Keep your redirect paths clean and direct.
Testing your redirects from another country
You can't verify country-based redirects without simulating traffic from different locations. Here are your options:
- VPN: Connect to a VPN server in the target country and visit your site. This is the most reliable method for testing the full redirect flow.
- GeoSwap preview mode: Our dashboard includes a preview mode that simulates visits from any country without needing a VPN.
- Browser developer tools: Chrome's DevTools can override geolocation for GPS-based targeting, but this does not affect IP-based geolocation, which is what most redirect systems use.
- Redirect checker tool: Verify the HTTP response code and redirect destination of any URL.
Approach 5: Nginx and Apache configuration
If you manage your own web server, you can handle country-based redirects at the web server level using MaxMind's GeoIP module. This is faster than application-level redirects because the server resolves the redirect before passing the request to your application code.
Nginx with GeoIP2 module
# nginx.conf — geo redirect by country
load_module modules/ngx_http_geoip2_module.so;
geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
auto_reload 24h;
$geoip2_country_code country iso_code;
}
map $geoip2_country_code $geo_redirect {
default "";
DE /de/;
FR /fr/;
JP /ja/;
BR /pt-br/;
}
server {
listen 443 ssl;
server_name yoursite.com;
# Skip redirect for bots
set $is_bot 0;
if ($http_user_agent ~* "(googlebot|bingbot|yandexbot|gptbot)") {
set $is_bot 1;
}
location = / {
if ($is_bot) {
break;
}
if ($geo_redirect != "") {
return 302 $geo_redirect;
}
# ... serve default content
}
}Apache with mod_geoip
# .htaccess — Apache geo redirect
GeoIPEnable On
GeoIPDBFile /usr/share/GeoIP/GeoLite2-Country.mmdb
# Skip bots
RewriteCond %{HTTP_USER_AGENT} !(googlebot|bingbot|yandexbot) [NC]
# Redirect German visitors
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^DE$
RewriteRule ^/$ /de/ [R=302,L]
# Redirect French visitors
RewriteCond %{HTTP_USER_AGENT} !(googlebot|bingbot|yandexbot) [NC]
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^FR$
RewriteRule ^/$ /fr/ [R=302,L]Pros: Very fast. The web server handles the redirect without involving your application code. Good for high-traffic sites.
Cons: Requires server access and configuration. Not available on managed hosting (Shopify, Webflow, most shared hosts). The GeoIP module must be compiled into Nginx or enabled in Apache. Database updates require a cron job.
Comparing all approaches
| Approach | Speed | SEO Safety | Platforms | Complexity |
|---|---|---|---|---|
| Edge workers | Under 10ms | High | Any | Medium |
| Server-side (Node/PHP) | 50-200ms | High | Own server only | Medium |
| Client-side JS | 500ms+ | Low | Any | Low |
| GeoSwap (no-code) | Under 10ms | High (automatic) | Any | Low |
| Nginx/Apache | Under 5ms | High | Own server only | High |
Building a region override mechanism
Every country redirect implementation needs an escape hatch. Visitors traveling abroad, using VPNs, or simply preferring a different language version should be able to override the automatic redirect. The standard approach is a cookie-based override:
// Region selector component (client-side)
function setRegionOverride(region) {
// Set a cookie that persists for 30 days
document.cookie = `geo_override=${region}; path=/; max-age=${30 * 24 * 60 * 60}; SameSite=Lax`;
window.location.href = `/${region}/`;
}
// Usage in your region selector dropdown
// <button onClick={() => setRegionOverride('de')}>Deutsch</button>
// <button onClick={() => setRegionOverride('fr')}>Francais</button>
// <button onClick={() => setRegionOverride('')}>English (default)</button>Your redirect logic (whether edge, server, or tool-based) should check for this cookie and skip the automatic redirect when it exists. The Cloudflare Worker and Express.js examples earlier in this guide include this check. Place your region selector in a visible location — the header or footer — where users expect to find it.
Real-world use cases
E-commerce: multiple regional stores
An online retailer with separate stores for the US, UK, and EU redirects visitors from each region to the appropriate storefront. Each store has its own inventory, pricing, and shipping configuration. The e-commerce geo-targeting guide covers this pattern in detail.
SaaS: localized pricing pages
A SaaS company shows different pricing to visitors from different regions, adjusted for purchasing power parity. Visitors from India see a lower price point than visitors from the US. See our localized pricing guide.
Media: region-restricted content
A streaming service or news publisher restricts certain content to specific regions due to licensing. Visitors from outside the licensed region are redirected to a page explaining the restriction or offering alternative content.
Affiliate marketing: multi-region links
Affiliate marketers need a single link that sends visitors to the correct Amazon storefront (amazon.com, amazon.co.uk, amazon.de, etc.) based on their country. Geo-targeted affiliate links are the solution.
Platform-specific guides
Different platforms have different constraints. We've written dedicated guides for the most popular ones:
- Geo-targeting for Shopify — working around Shopify Markets limitations
- Geo-targeting for WordPress — plugins vs scripts vs server-side
- Geo-targeting for Webflow — adding geo-redirects to a static site
Geo Targetly vs building it yourself
Geo Targetly is the most well-known paid geo-targeting tool, charging $9-349/month depending on features and traffic. Before building a custom solution or choosing a tool, here is how the options compare:
- Geo Targetly: $9-349/month. Per-product billing (redirect, content, links are separate subscriptions). Pageview quotas that stop working when exceeded. Client-side JavaScript execution. See our full pricing breakdown.
- Custom Cloudflare Worker: Free tier covers 100,000 requests per day. Full control. Requires coding and maintenance.
- GeoSwap: Free, no pageview limits, edge-powered, no code required. All products (redirect, content, links) included. See our detailed Geo Targetly comparison.
Frequently asked questions
Is redirecting visitors by country legal?
Yes. IP-based geo-targeting is legal in all major jurisdictions. IP addresses are considered personal data under GDPR, but geo-targeting based on IP lookup (without storing the IP) falls under the “legitimate interest” basis. You should still disclose the practice in your privacy policy.
Will country redirects hurt my SEO?
Not if you implement them correctly. Use 302 redirects, explicit country rules (not exclusion rules), hreflang tags, and bot-transparent architecture. Read our complete SEO safety guide for the full breakdown.
What about visitors using VPNs?
VPN users will be redirected based on the VPN server's country, not their actual country. This is expected behavior. The important thing is to always provide a manual region selector so visitors can override the automatic redirect. According to Surfshark, approximately 31% of internet users worldwide used a VPN in 2023, so this is not an edge case.
How fast are country-based redirects?
Edge-side redirects (Cloudflare Workers, Vercel Edge Middleware) resolve in under 10 milliseconds. Server-side redirects add the round-trip time to your origin server. Client-side JavaScript redirects are the slowest — the page loads first, then the API call fires, then the redirect happens, often taking 500ms or more.
Can I redirect based on state or city, not just country?
Yes, though accuracy decreases. Country-level detection is 99.5% accurate, state-level is 80-90%, and city-level is 70-80%. For state-level use cases (like showing different content for California vs Texas), IP geolocation works well. GeoSwap's GeoRedirect supports country, state, and city-level targeting.
Do I need country redirects if I have hreflang tags?
Usually yes. Hreflang tags tell search engines which page version to show in search results for each country. Geo redirects handle the visitor who lands on the wrong version directly (via a shared link, bookmark, or direct URL). They solve different problems and work best together. See our geo redirect vs hreflang comparison.
How do I test country redirects before launching?
Use a VPN to connect from each target country and visit your site. Verify the redirect destination and HTTP status code. GeoSwap also offers a built-in preview mode that simulates visits from any country without needing a VPN. Our complete guide to testing from another country covers six methods in detail.
What is the difference between geo-redirecting and geo-blocking?
A geo redirect sends visitors to a different, relevant page (like a localized version of your site). A geo block prevents access entirely, usually for compliance reasons (sanctions, licensing restrictions). Redirects improve the user experience; blocks restrict it. Most businesses need redirects, not blocks.
Should I redirect all pages or just the homepage?
Start with the homepage and key landing pages. Redirecting every page on your site can create complex redirect chains and confuse search engines. For deep pages, hreflang tags are often a better solution than redirects — they let search engines serve the right version in results without forcing a redirect on every visit.
Redirecting visitors by country is one of the most impactful things you can do for an international website. Edge-side redirects are the gold standard — fast, flicker-free, and SEO-safe. Whether you build it yourself with Cloudflare Workers or set it up in five minutes with GeoSwap, the important thing is to get it right: 302 redirects, explicit rules, hreflang tags, and always let bots through. Check out our geo redirect documentation for the full setup walkthrough.
