Created
October 9, 2021 13:24
-
-
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
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
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, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '&').replace(/'/g, '''); | |
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