Skip to main content
How To...Performance

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 => {
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": "",
  "EU": "",
  "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