Skip to content

Instantly share code, notes, and snippets.

@heguro
Created October 9, 2021 13:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heguro/a5d82bfd4325e26698ec9fec7bb04bc1 to your computer and use it in GitHub Desktop.
Save heguro/a5d82bfd4325e26698ec9fec7bb04bc1 to your computer and use it in GitHub Desktop.
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