Created
August 24, 2018 08:23
-
-
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.
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
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