Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CloudFlare worker to rewrite Host header for S3
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
const lookup = {
"mybucket.example.com": "https://my-s3-bucket.s3.us-east-1.amazonaws.com",
};
async function handleRequest(origRequest) {
const origUrl = new URL(origRequest.url);
const newOrigin = lookup[origUrl.hostname];
let request = origRequest;
if (newOrigin) {
const newUrl = origRequest.url.replace(origUrl.origin, newOrigin);
request = new Request(newUrl, {
body: origRequest.body,
headers: origRequest.headers,
method: origRequest.method,
redirect: origRequest.redirect
});
}
const response = await fetch(request);
// console.log({ response });
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment