HOW TO: Use Cloudflare to handle Country-based redirects

February 22, 2020

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://403.ie/us",
  "EU": "https://403.ie/eu",
  "FR": "https://403.ie/fr"
}

Cloudflare uses ISO 3166-1 alpha-2 for country values. See the Wikipedia page for a full list of values.