Search code examples
amazon-web-servicesamazon-ec2dnsamazon-cloudfrontstatic-site

CloudFront static website and EC2 API on same domain


I have my static website hosted on CloudFront.

Is there a way for me to use the same domain name but different port for API calls to an EC2 instance?

Eg. example.com:3000 should be redirected to the EC2 instance, while example.com (aka example.com:443 or example.com:80) should be redirected to CloudFront.


Solution

  • It's not possible to discern the target host based on port number. The DNS name alone determines where your browser connects to.

    However, you can still achieve what you want, just not by port number.

    You can configure your CloudFront distribution to forward requests to your static website or API depending on the path in the URL.

    To accomplish this, you would configure multiple origins and multiple behaviours in your CloudFront distribution:

    • /api/* -> EC2 origin
    • Everything else -> Static website origin

    To your browser, it appears as a single website. When you request https://www.example.com/page1.html, CloudFront will forward the request to the static webiste. When you request https://www.example.com/api/MyRestMethod, CloudFront will forward the request to your EC2.

    This also allows you to use the same ACM certificate for HTTPS between your API and your static website.