Skip to content

Instantly share code, notes, and snippets.

@zerolab
Last active April 2, 2020 08:45
Show Gist options
  • Save zerolab/3b3fc3420d5562d04b47053dc5b4f843 to your computer and use it in GitHub Desktop.
Save zerolab/3b3fc3420d5562d04b47053dc5b4f843 to your computer and use it in GitHub Desktop.
Cloudflare Worker - bulk regex 404s
/**
* 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