How to Redirect Traffic Based on Country Using Cloudflare Workers

When running a website that serves multiple countries, it’s often useful to redirect users to their region-specific domain. Cloudflare Workers provide a powerful way to implement country-based redirection efficiently. In this guide, we’ll walk through how to set up geo-based redirection using Cloudflare Workers.

Why Use Cloudflare Workers for Geo-Redirects?

Cloudflare Workers allow you to execute JavaScript at the network edge, meaning redirects happen before requests even reach your origin server. This results in:

  • Faster redirects (handled at the edge, not your server)
  • Reduced server load (Cloudflare processes requests before hitting your backend)
  • Custom logic (redirects based on country, user-agent, headers, etc.)

Step 1: Create a Cloudflare Worker

  1. Log in to Cloudflare and select your domain.
  2. Navigate to Workers & Pages in the sidebar.
  3. Click Create Application, then Create Worker.
  4. In the code editor, delete the default script and replace it with the following:
addEventListener("fetch", event => {
    event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
    // Get the visitor's country from Cloudflare headers
    let country = request.headers.get("cf-ipcountry") || "XX";

    // Define country-specific redirects
    let redirectMap = {
        "KE": "https://example.co.ke",
        "UG": "https://example.co.ug",
        "NG": "https://example.ng",
        "RW": "https://example.co.rw",
        "TZ": "https://example.co.tz"
    };

    let url = new URL(request.url);
    let hostname = url.hostname.replace("www.", ""); // Normalize hostname

    // Exclude the '/blog' folder from redirection
    if (url.pathname.startsWith("/blog")) {
        return fetch(request); // Serve normally
    }

    // Redirect based on country
    if (redirectMap[country]) {
        return Response.redirect(redirectMap[country] + url.pathname, 301);
    }

    // Default behavior: Serve the original request
    return fetch(request);
}
  1. Click Save and Deploy.

Step 2: Attach the Worker to Your Domain

Once your Worker is ready, you need to assign it to your domain:

  1. Go to Workers & PagesRoutes
  2. Click Add Route
  3. Enter the following routes:
    • example.com/*
    • www.example.com/*
  4. Attach your Worker to both routes.
  5. Set Failure Mode to Fail Open (Proceed) to prevent downtime if Worker request limits are reached.
  6. Click Save and Deploy.

Step 3: Configure DNS for www (If Needed)

To ensure www.example.com also redirects properly, check your DNS settings:

  1. Go to DNS Settings in Cloudflare.
  2. Check if a CNAME record exists for www pointing to example.com.
  3. If missing, add this record:
    • Type: CNAME
    • Name: www
    • Target: example.com
    • Proxy Status: Proxied (Orange Cloud ☁️)
  4. Save changes.

Step 4: Test the Redirects

Once everything is set up, test the redirection:

  • Visit https://example.com/ and https://www.example.com/.
  • Use a VPN or modify headers (e.g., with Postman) to simulate requests from different countries.
  • Ensure pages inside /blog are not redirected.

Conclusion

By using Cloudflare Workers, you can efficiently redirect users to country-specific domains without relying on server-side logic. This improves performance, reduces server load, and ensures a seamless experience for visitors worldwide.

With this setup, users from Kenya, Uganda, Nigeria, Rwanda, and Tanzania will be redirected to their respective domains while other users remain on the main site. The /blog section remains accessible without redirection.

Need further customization? Cloudflare Workers support additional conditions, such as redirects based on language, user-agent, or IP range!


Frequently Asked Questions (FAQs)

Q1: Why is my www version not redirecting?
Ensure you added a separate route for www.example.com/* and that your DNS settings include a CNAME for www pointing to example.com.

Q2: Can I use this for subdirectories like example.com/shop?
Yes! The script automatically redirects all pages (/*). You can modify it to exclude more paths like /blog if needed.

Q3: What happens if a user is in a country not listed?
They stay on example.com without redirection.

Q4: How do I test Cloudflare Workers before deploying?
Use the Workers Preview URL (e.g., your-worker.example.workers.dev) to test before attaching it to your domain.


Now your website is optimized for global traffic with geo-based redirections! 🚀

Leave a Comment