Here’s how to make api.my-app.com available under my-app.com/api, using CloudFront or Cloudflare.
If both my-app.com and api.my-app.com are hosted in AWS, you can route requests to these instances using the CloudFront CDN.
Here’s what you’ll need to do:
-
Create a CloudFront distribution
-
Create two origins, one pointing to the EC2 instance (or an S3 bucket) with
my-app.com, and another pointing to the EC2 instance withapi.my-app.com: -
Configure Behaviors to route
/apirequests to theapi.my-app.comserver: -
Point
my-app.comto the CloudFront distribution.
Unfortunately, to prevent abuse, Cloudflare doesn’t support reverse proxying (unless you’re on the Enterprise plan).
This means that, to proxy /api requests to api.my-app.com, we’ll have to deploy a Worker script.
Cloudflare Workers are scripts that run on each Cloudflare server. A script receives every incoming request and tells Cloudflare how to handle that request. Here’s a script that would tell Cloudflare to proxy /api requests to api.my-app.com:
addEventListener('fetch', (event) => {
const url = new URL(event.request.url)
// If this is a request to /api/...
if (url.pathname.startsWith('/api/')) {
// Build the proper API URL
const apiServerURL = 'https://api.my-app.com/' + url
// Send the request to the API
const apiResponsePromise = fetch(apiServerURL, event.request)
// Pass the API response promise back to the user
event.respondWith(apiResponsePromise)
return
}
// Otherwise, just proxy the request unmodified
event.respondWith(fetch(event.request))
})To deploy the worker, use Cloudflare’s tool called wrangler. Follow steps from the Cloudflare’s guide to set up and deploy it.
After deploying the worker, go to its routes and configure it to handle requests to my-app.com/*.

