IP Redirects

If you need to redirect users based on their IP address for whatever reason you do it with the following worker:

addEventListener('fetch', event => {
  event.respondWith(fetchAndApply(event.request))
})

async function fetchAndApply(request) {

    const country = request.headers.get('Cf-Ipcountry').toLowerCase() 
    let url = new URL(request.url)

    const target_url = 'https://'+url.hostname+'/'+country
    const target_url_response = await fetch(target_url)

    if(target_url_response.status == 200) {
        return new Response('', {
          status: 302,
          headers: {
            'Location': target_url
          }
        })     
    } else {
        return response
    }
}

This utilizes the existing Cf-Ipcountry header, which is a two letter country code detected by Cloudflare on the edge with every request and passed to the origin. The worker appends this country code onto the original request URL and checks if that new URL exists.

Example - A user types in mysite.com from Canada. The worker will detect the country and ping mysite.com/ca to see if it exists. If a 200 response is returned the user is redirect to mysite.com/ca. If the response was not a 200 they proceed to the original destination.

IP redirection at the edge. You can see a detailed explanation of this recipe and more on our Cloudflare Workers Review

11 Likes

It says there is a detailed explanation but I couldn’t find any info on how to actually set this up

And it seems to only be for one country, how do I set this up to redirect traffic from two countries?

Thanks

:wave: @seanchk,

Documentation on Cloudflare Workers is available here:

Cloudflare Workers documentation · Cloudflare Workers docs

— OG

Thanks Oliver.

Any instructions for non developers?

Like some very simple step by step instructions?

I’ve had issues with this code, where it the worker throws an exception if there isn’t a page set up for the country code. Does anyone know how to direct all other country IP’s to another url? Any help appreciated!

Is there any way to set a Worker to redirect a specific list of IPs rather than by geolocation? I want to prevent access to a certain page (via redirect, not block) by about 6 IPs, but I don’t want all IPs from that country redirecting. If there’s a forum I can be pointed to, I’d be happy to check it out. Thank you!