Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Serve S3 images from your own domain using Cloudflare worker
addEventListener('fetch', event => {
* When we receive a request, fetch it from our S3 bucket
* For example, a request for:
* will be fetched from:
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 = ''
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
Copy link

lfjeff commented Jun 11, 2018

This script runs on Cloudflare as a worker script and allows you to serve files stored on your S3 bucket. The files appear to be coming from your domain and the S3 bucket is hidden.

Of course, this script is no substitute for maintaining proper security on your S3 bucket.

Copy link

MarsVard commented Dec 7, 2020

Does caching still work using this method?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment