Forked from lfjeff/serve_s3_images_from_own_domain.js
Created
September 23, 2022 08:59
-
-
Save SiZapPaaiGwat/3cf9dd1e0fcd87024d195645dc5be619 to your computer and use it in GitHub Desktop.
Serve S3 images from your own domain using Cloudflare worker
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)) | |
}) | |
/** | |
* When we receive a request, fetch it from our S3 bucket | |
* | |
* For example, a request for: | |
* https://mydomain.com/images/castle01.jpg | |
* will be fetched from: | |
* https://s3-de-central.profitbricks.com/my-images/test-folder/castle01.jpg | |
*/ | |
async function handleRequest(request) { | |
// map our request folder to the s3 folder | |
let requestFolder = '/images' | |
let s3Folder = '/my-images/test-folder' | |
let url = new URL(request.url) | |
let origPathname = url.pathname | |
// fetch from the folder on our s3 bucket | |
url.hostname = 's3-de-central.profitbricks.com' | |
url.pathname = origPathname.replace(new RegExp('^'+escapeRegExp(requestFolder)), s3Folder) | |
return await fetch(url, request) | |
} | |
function escapeRegExp(string) { | |
return string.replace(/[.*+?^${}()|[\]\\\/]/g, '\\$&'); // $& means the whole matched string | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment