IP redirect by country

Note: Had to use [dot] to type out URLS

I want to set up a route so users with Australian or New Zealand IP’s are redirected from waterhaul[dot]co to waterhauls[dot]com[dot]au. All other coutnries shoud be unaffacted and load waterhaul.co

I’ve been using the code below, however it works for AU/NZ IP’s (they get redirected) but I get an error for other countries. Is that because it gets stuck in an endless loop of redirecting to waterhaul[dot]co? Would massivley apprechiate any code revisions

// Configuration to map country codes to regional stores
const regionalStores = new Map([
[“GB”, “waterhaul[dot]co”],
[“AU”, “waterhauls.com.au”],
[“NZ”, “waterhauls.com.au”],

]);

addEventListener(“fetch”, event => {
event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
// Read the IP address from Cloudflare
const country = request.headers.get(“cf-ipcountry”);

// Set our default regional store
// This is used if there’s no matching store configuration
let regionalStore = regionalStores.get(“GB”);

// Set the new regional store, if it’s set in the regionalStores map
if (regionalStores.has(country)) {
regionalStore = regionalStores.get(country);
}

// Redirect the user to the new URL
return Response.redirect(“https://” + regionalStore);
}

Good thing you have a local, @eva2000, who loves using country codes and Workers.

Maybe inspiration from example at https://developers.cloudflare.com/workers/examples/country-code-redirect

2 Likes