Redirecting website to country-based with Worker

Hello,

I am trying to redirect a website with country-based. I wrote the worker script and with the preview and curl -v is working as expected. But when I am attaching the route with my domain, it is not redirecting. Where as I have set the subdomains in my dns as us..org,in..or and so on.

Here is my script:

/**

  • A map of the URLs to redirect to
  • @param {Object} countryMap
    */
    const countryMap = new Map ([
    [“US”, “us..org”],
    [“EU”, “eu..org”],
    [“IN”, “in..org”],
    [“UK”, “uk..org”]
    ]);

addEventListener(‘fetch’, event => {
event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
const country = request.headers.get(‘cf-ipcountry’);

let regionalStore = countryMap.get(“US”)

if (countryMap.has(country)) {
regionalStore = countryMap.get(country);
}
return Response.redirect(“https://” + regionalStore);
}

Please help me to find a solution and enable the domain to route as expected.

Have you looked at the country code redirect example in the Cloudflare Workers documentation?

async function redirect(request) {

  const country = request.cf.country

  if (country != null && country in countryMap) {
    const url = countryMap[country]
    return Response.redirect(url)
  }
  else {
    return await fetch(request)
  }
}

const countryMap = {
  GB: "https://yourdomain.com/gb",
  JE: "https://yourdomain.com/gb",
  IM: "https://yourdomain.com/gb",
  GG: "https://yourdomain.com/gb",
  IN: "https://yourdomain.com/in",
  US: "https://yourdomain.com/us",
}

async function handleRequest(request) {
  return redirect(request)
}

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request))
})

Above is a working example from my implementation.
Hope it helps you

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.