Home > Blockchain >  Route specific S3 hosted website path to EC2
Route specific S3 hosted website path to EC2

Time:12-14

I'm hosting my website files on a S3 bucket using the static website hosting feature, however; since my project is build under a framework that exports some API routes using relative paths, I run into the problem that those requests fail because S3 is not meant to serve those API requests.

My intended solution here was to create a Node server that runs on a container under a EC2 instance, and then have any requests made by the static website files to domain.com/api be served by this server on EC2.

For example, suppose my automatically generated static files are hosted on a bucket with the name domain.com, the user would then access this page and the static files will make a request using relative path to /api/getSomeInfo, the request URL will then be domain.com/api/getSomeInfo, in that case I would like to make that request to the node server running on EC2 and give back the response to the page that made the request.

How can this be accomplished?

I tried using the s3 static website routing rules, but that did not work.

This was the rule I tried:

{
  "Condition": {
    "KeyPrefixEquals": "api/"
  },
  "Redirect": {
    "HostName": "ec2-domain.com", //Idealy I would like this to be the same domain. Eg. domain.com; In which case this rule wouldn't even be necessary
    "HttpRedirectCode": "301",
    "Protocol": "https",
    "ReplaceKeyPrefixWith": "api/"
  }
}

What I ended up doing was serving both the static files and the API routes using that node server running on EC2, but I would like to serve the static files using S3 and maybe CloudFront for performance reasons.

Thank you.

CodePudding user response:

Consider using CloudFront, which supports multiple sources ("origins" in CloudFront-speak, like S3 and EC2) and path-specific configuration ("behaviours").

See the AWS Knowledge Center Article Can I use a single CloudFront web distribution to serve content from multiple origins using multiple behaviors?. Spoiler alert: Yes.

  • Related