HOW TO: Use Cloudflare to handle Country-based redirects
What is this for?
You have a multilingual or multi-regional website and want to have redirects handled on Cloudflare’s edge with Workers (instead of inside something like WordPress or directly on your server) for a nice performance gain.
Head to the Workers page in your Cloudflare account and click Launch Editor:
On the newer dashboard layout, click Create a Worker and then Quick Edit. Add the following snippet into the Script box:
async function handleRequest(request) {
return redirect(request, 'subdomain')
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
function redirect(request) {
const country = request.headers.get('cf-ipcountry')
const url = countryMap[country]
return Response.redirect(url)
}
/**
* List your country codes and intended redirect destinations here
*/
const countryMap = {
"US": "https://403page.com/us",
"EU": "https://403page.com/eu",
"FR": "https://403page.com/fr"
}
Cloudflare uses ISO 3166-1 alpha-2 for country values. See the Wikipedia page for a full list of values.
More fun Cloudflare worker stuff:
HOW TO: Use Cloudflare to enable Basic Auth on a subdirectory
HOW TO: Use Cloudflare to reverse proxy a subdirectory
HOW TO: Block non-Cloudflare requests to your site with a Worker
HOW TO: Support .webp on Cloudflare’s edge with a Worker
HOW TO: Create a downtime failover for your site with a Cloudflare Worker