IP Redirects

recipe-exchange

#1

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