AWS S3 Route Rewrite

Viewed 207

I would like to setup my S3 bucket to rewrite the path of the route /api to a API Gateway URL.

So take the following:

example

  • User goes to website bacon.com
  • Website goes from Cloudflare DNS to S3 bucket
  • Website is a react app
  • React app makes a call to api which is bacon.com/api
  • S3 rewrites /api path to api gateway url https://ljsdflkjlsdk.execute-api.us-east-1.amazonaws.com/dev

I was able to get this to work here:

s3

however, it forwards the URL to that API gateway URL which is not desired.

I'm not entirely sure this is possible. I'm thinking it might require either me implementing something like Route53 or writing a cloudflare worker to handle the rewrite?

Thanks in advance for your help!

1 Answers

So you want to proxy requests to the /api path to your backend API, while other routes, e.g. /login are served by the React app.

I may be wrong but I think neither S3 (as a static hosting provider) nor Route 53 (as a DNS tool) can help with that.

Since you mentioned you're already using Cloudflare, you can do this with CF Workers with little effort though!

  1. Make sure bacon.com is proxied by CF (orange cloud ON on DNS tab)
  2. Create a new worker with this code:
const backendUrl = "https://ljsdflkjlsdk.execute-api.us-east-1.amazonaws.com/dev"

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

/**
 * Respond to the request
 * @param {Request} request
 */
async function handleRequest(request) {
  return fetch(backendUrl, request)
}
  1. Associate the worker with the /api path on the Workers tab for the bacon.com
  2. bacon.com/api is now a proxy sending requests to the backend url!
Related