Last active
April 2, 2020 08:45
-
-
Save zerolab/3b3fc3420d5562d04b47053dc5b4f843 to your computer and use it in GitHub Desktop.
Cloudflare Worker - bulk regex 404s
This file contains 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
/** | |
* Sets up routes and 404 any that match the 404 map | |
* @param {Request} request | |
*/ | |
async function handleRequest(request) { | |
let requestURL = new URL(request.url) | |
let path = requestURL.pathname | |
if (should404(path)) { | |
return new Response('Sorry, not found', { | |
status: 404 | |
}); | |
} | |
return fetch(request) | |
} | |
addEventListener('fetch', async event => { | |
event.respondWith(handleRequest(event.request)) | |
}) | |
const pathMap = [ | |
/^\/autodiscover\/autodiscover\.xml/, | |
/^\/sites\/all\//, | |
/^\/sites\/default\/files\/js/, | |
/^\/sites\/default\/files\/css/, | |
/^\/sites\/default\/files\/styles/, | |
/^\/sites\/default\/files\/civimail/, | |
/^\/sites\/default\/files\/.*\.png$/, | |
/^\/sites\/default\/files\/.*\.jpg$/, | |
/^\/sites\/default\/files\/.*\.gif$/, | |
] | |
function should404(path) { | |
for (key in pathMap) { | |
let r = new RegExp(pathMap[key]); | |
if (r.test(path)) { | |
return true; | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment