Created
April 19, 2022 01:55
-
-
Save MogulChris/477cd48f38de1b14f906f919a6b8cdde to your computer and use it in GitHub Desktop.
Cloudflare service worker to redirect to country subdirectories
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Based on https://community.cloudflare.com/t/geoip-redirection-worker/14414 | |
//This assumes you have region-specific sites set up like so | |
//www.company.com - global landing page where this worker runs | |
//www.company.com/us/ | |
//www.company.com/au/ | |
//in our case we are only changing paths/dubdirectories, not domains. Map country codes to subdirectories. | |
var redirects = { | |
'US' : 'us', | |
'AU' : 'au' | |
}; | |
//user agents containing any of these strings don't get redirected | |
var bypass_ua = ['googlebot','bing']; | |
addEventListener('fetch', event => { | |
event.respondWith(Redirect(event.request)) | |
}) | |
function byPass(request){ | |
var length = bypass_ua.length; | |
for(var i = 0; i < length; i++) { | |
if(request.headers.get('user-agent') && request.headers.get('user-agent').includes(bypass_ua[i])) { | |
return true; | |
} | |
//any other conditions where you want to bypass redirects should return true here | |
} | |
return false; | |
} | |
function mapCountry(country_code){ | |
if(country_code in redirects) { | |
return redirects[country_code]; | |
} | |
return ''; | |
} | |
/** | |
* Fetch and log a given request object | |
* @param {Request} request | |
*/ | |
async function Redirect(request) { | |
var url = new URL(request.url); | |
correctPath = mapCountry(request.headers.get('CF-IPCountry')); | |
if(byPass(request) || correctPath == ''){ //nothing to do | |
console.log('no redirect'); | |
const response = await fetch(request) | |
return response | |
} | |
//check we are on the global landing page (/) and have somewhere else to go | |
if (correctPath != '' && url.pathname == '/'){ | |
url.pathname = '/' + correctPath; | |
console.log('redirecting to '+url.href); | |
return new Response('', { | |
status: 301, | |
headers: { | |
'Location': url.href | |
} | |
}) | |
} | |
//fallback | |
console.log('no redirect'); | |
const response = await fetch(request) | |
return response | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment