Given an existing server on Elastic Beanstalk, this tutorial describes how to
connect it to Cloudfront, including using Route53 and managing CORS.
This post assumes that you already have an environment in Elastic Beanstalk.
Step 1: Application Load Balancer
Follow the [Application Load Balancer] documentation to check if a load balancer
exists; if not, then add one. If this is a server receiving requests from a web
frontend, then you should have listeners at 443 HTTPS and 80 HTTP, wit han SSL
certificate connected to the HTTPS port.
Step 2: Create a CloudFront distribution
Create a new CloudFront distribution. The most important step here is to select
the appropriate origin under – Elastic Load Balancers – for Origin Domain
- If you have multiple environments, such as staging and production, I’m
actually not sure how to distinguish the two (I used the creation date of
the load balancer by searching for “load balancers” and going to EC2 in the
search box above). Find some means to select the appropriate one as the
Origin Domain Name.
- Give a meaningful Origin ID. You should be able to use any string here,
pick one that you can remember.
- Select Redirect HTTP to HTTPS.
- Pick Allowed HTTP Methods based on what your app is doing; if you want to
be safe or aren’t sure, select the longest list here. This option is simply
what’s allowed, what’s actually cached ony includes GET, HEAD, and
optionally OPTIONS (see Cached HTTP Methods section).
- For Cache Policy, this is totally application dependent; you can pick a
default for now and change it later, but this is application-specific. If
you simply want to test things first, I suggest making a custom cache policy
with all cache durations set to 0.
- For Origin Request Policy, to get CORS to work (at least in the case of my
application), create a new policy with Whitelist:
this, you may see CORS errors from a web frontend. These will allow
preflight CORS requests to properly propagate to your server through
Anything can be changed later; you can save here or read the next step for
setting up a custom domain.
Step 3 (optional): Repoint your domain to CloudFront
If you have a custom domain name like
api.foo.com, then you’ll want to set it
in Alternate Domain Names as well as setting up the SSL certificate. If this
is already in Route 53, clicking Request or Import a Certificate with ACM
should be enough.
If you already aliased
api.foo.com to your Elastic Beanstalk endpoint,
then, after the distribution is created, you’ll need to create a new alias
pointing to the CloudFront endpoint and removing the old
api.foo.com record in
Route53 (presumably this is a CNAME or A record).
At this point, you should have a CloudFront distribution pointing to the load
balancer on top of your Elastic Beanstalk environment. If you followed step 3,
api.foo.com will point to your CloudFront distribution, otherwise you can use
*.cloudfront.net domain shown under “CloudFront” (also connectable via
Route53). Happy caching!