Skip to content

Instantly share code, notes, and snippets.

@vdbelt
Created August 24, 2018 08:23
Show Gist options
  • Save vdbelt/bd2a3d6466d6bc381f639875a6649d27 to your computer and use it in GitHub Desktop.
Save vdbelt/bd2a3d6466d6bc381f639875a6649d27 to your computer and use it in GitHub Desktop.
Blocks certain countries from accessing your page, while giving the flexibility to whitelist certain paths.
addEventListener('fetch', event => {
event.respondWith(byPassOrBlock(event.request))
})
async function byPassOrBlock(request) {
let url = new URL(request.url)
let blockedCountries = ['XX']
let whitelistedPaths = ['/about*']
for (let i=0; i<whitelistedPaths.length; i++) {
if (new RegExp("^" + whitelistedPaths[i].split("*").join(".*") + "$").test(url.pathname)) {
return fetch(request)
}
}
if (blockedCountries.includes(request.headers.get('cf-ipcountry'))) {
// Return a Forbidden response
return new Response('Sorry, this page is not available.', { status: 403, statusText: 'Forbidden' })
// Or, alternatively, return a redirect. Make sure to whitelist this to avoid loops
// return Response.redirect('https://example.com')
}
return fetch(request)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment