CloudFlare worker to rewrite Host header for S3
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)); | |
}); | |
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