Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
cloudflare workers script; http to https redirect, with /file/<bucket-name>/ deletion for backblaze b2. https://scrapbox.io/heguro/Backblaze_B2_+_Cloudflare
addEventListener("fetch", (event) => {
event.respondWith(
handleRequest(event.request).catch(
(err) => new Response(err.stack, { status: 500 })
)
);
});
/**
* @param {Request} request
* @returns {Promise<Response>}
*/
async function handleRequest(request) {
const url = new URL(request.url);
if (url.protocol === 'http:') {
// https にする
url.protocol = 'https:';
// URL についてる /file/<bucker-name> を外す
url.pathname = url.pathname.replace(/^\/file\/[\w-]+\//, '/');
// bucket 内にホスト名のディレクトリを作って運用してる場合それも外す
if (url.pathname.startsWith(`/${url.hostname}/`)) {
url.pathname = url.pathname.replace(/^\/[^\/]+\//, '/');
}
const htmlUrl = url.href.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&amp;').replace(/'/g, '&#39;');
return new Response(
`<!DOCTYPE html><html><head><title>Redirecting</title></head><body>Redirecting to <a href="${
htmlUrl
}">${
htmlUrl
}</a></body></html>`,
{
status: 301,
headers: {'Location': url.href}
}
);
}
return new Response('this script does not accept https');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment