Insights

How To Setup Simple Geo Redirection In Cloudflare

Need For Simple Geo Redirection

You've got Cloudflare. You may or may not be using it. However, you need to have a way to setup simple geo redirection. Perhaps you've got half a dozen country specific sites that you want to direct people to if they hit your main site. Let's do that.

The simple answer is you can, with Cloudflare Workers.

What Are Cloudflare Workers?

Well, for one, they are a truly powerful way of handling complex tasks (or even simple ones) in a manner that makes sense to Administrators and Developers. Cloudflare Workers provides for a serverless execution environment for handling requests and determining what happens to those requests. The beauty is not only is there abundant documentation along with examples, there's even a Playground to test out it's capabilities.

That's all fine and dandy, but the true beauty is that each worker is written entirely in JavaScript. So we're not talking some proprietary language you need to learn. If you know JavaScript, you can create a worker.

Let's Build A Geo Redirection Worker

Once you've logged into your Cloudflare environment, head on over to the Workers area and create a new worker.

The Workers area in Cloudflare allows users to add and create new Workers.

Inside the worker editor you'll see the default worker setup. On the left is the default code, on the right is a preview window and inspection tools.

The default Workers setup in Cloudflare has code on the left and preview window and inspection tools on the right.

What we will want to do is alter the handleRequest function to detect the country of origin of the visitor and redirect them appropriately. If you're using one worker for multiple purposes you'll likely need to create a wrapper such that the geo redirect only works on a specific URL.


addEventListener('fetch', function(event) {
    const { request } = event
    const response = handleRequest(request).catch(handleError)
    event.respondWith(response)
    })

// handleRequest function 
async function handleRequest(request) {
    const { method, url } = request
    const { host, pathname } = new URL(url)
    
    if ((host == "www.abccompany.com" || host == "abccompany.com") && pathname == "/")){
        const country = request.cf.country
        if (country != null && country in countryMap) {
            const countryUrl = countryMap[country]
            return Response.redirect(countryUrl)
        }
    }
    return fetch(request)
}

// Country Dictionary Map
const countryMap = {
    US: "https://us.abccompany.com/",
    CA: "https://www.abccompany.ca/",
    UK: "https://www.abccompany.com/en-gb/",
    }    

So what's all happening?

Let's Break It Down

As in our case we're using the worker for multiple purposes we want to make sure the geo redirection only happens on the root and only on the WWW CNAME and the root A record for the domain. If you wanted to focus the worker using a route to only run if the worker was www.abccompany.com/ you could clean up the code further.

After that we grab the country code of the request from request.cf.country and use that to map against our countryMap dictionary. The values for which are the destination URLs we want the visitor to be redirected to depending on what the country is.

Can We Test It?

The challenge with testing a geo redirect in Cloudflare is that you are unable to validate your lookup is working while in the preview area of the worker editor. The reason being is that the request.cf object doesn't exist there. It only exists when the worker has been published. So if you modify your script to trigger if host == "<worker name>.abcworkers.workers.dev". That way you can hit the worker directly in the browser and validate that it redirects accordingly.

Utilize A VPN To Validate Locations

You could rely on clients to let you know the redirect is working, or you could utilize a VPN to properly test it. This way your IP will trigger the appropriate country code value and you can ensure the redirection is working as intended.

👋 Hey Sitecore Enthusiasts!

Sign up to our bi-weekly newsletter for a bite-sized curation of valuable insight from the Sitecore community.

What’s in it for you?

  • Stay up-to-date with the latest Sitecore news
  • New to Sitecore? Learn tips and tricks to help you navigate this powerful tool
  • Sitecore pro? Expand your skill set and discover troubleshooting tips
  • Browse open careers and opportunities
  • Get a chance to be featured in upcoming editions
  • Learn our secret handshake
  • And more!
Sitecore Snack a newsletter by Fishtank Consulting
 

Meet David Austin

Development Team Lead | Sitecore Technology MVP x 3

📷🕹️👪

David is a decorated Development Team Lead with Sitecore Technology MVP and Coveo MVP awards, as well as Sitecore CDP & Personalize Certified. He's worked in IT for 25 years; everything ranging from Developer to Business Analyst to Group Lead helping manage everything from Intranet and Internet sites to facility management and application support. David is a dedicated family man who loves to spend time with his girls. He's also an avid photographer and loves to explore new places.

Connect with David