A common use case for S3 is hosting content that should not be available to the public, but needs to be made available to specific user(s) or for a specific length of time. A great example of this is granting access to digital files after a purchase or subscription payment.
In this case, I needed the domain to be a first-party subdomain, rather than a default Amazon AWS domain, due to same-origin policy requirements.
Hat-tip to Fershad Irani for an initial version, which I modified to suit my needs.
Set up the AWS Bucket
- Create a bucket
- Prevent all public access to objects in the bucket
- Upload files
Configure a Cloudflare Worker
- Go to CloudFlare > Workers & Pages > Overview and create a new application
- Add the worker code below, modifying line 8 to use your bucket name
- Publish the worker
- If you already added the subdomain under the DNS tab pointing to anywhere, delete that before proceeding
- View the worker and go to the Triggers tab
- Under Custom Domains, add a custom domain (documentation) and enter your custom subdomain
- Under Routes, add a route for your custom subdomain