Enable Cors for AWS Cloudfront and S3  hosted apps

Enable Cors for AWS Cloudfront and S3 hosted apps

Sometimes you need to enable cors for AWS Cloudfront and S3 hosted sites.My case is : I want to host assets from my Playcanvas project on my cdn which is hosted on AWS.We will do it quickly

At Start

As i said we will do it quickly.I dont get into the initial steps because i assumed you did it. First of all we create S3 and load the assets that we want.Secondly , we create a cloudfront distrubution for this bucket and deploy it.

Straight to the point 🧭

The main part of the article comes.Now we have a s3 bucket and a bounded cloudfront distrubution.

The S3 part

In S3 part edit the cors setting of bucket like this.

For those who doesnt know where the edit esction is , it's in the **permissions** section of the s3 bucket

aws s3 cors
[
  {
    "AllowedHeaders":[],
    "AllowedMethods":[
      "GET"
    ],
    "AllowedOrigins":[
      "*"
    ],
    "ExposeHeaders":[]
  }
]

Cloudfront part

In the clodfront distrubution , edit tdistrubution and go to behaviour tab. As you see below image , there is a cache key and origin request section.When we create a new distrubution on Cloudfront , it creates default policies automatically.So we should edit these policies to modify the request origin.

aws s3 cors

There are two links in this section.**Create policy & View policy **

Ok , Lets create **cache policy** & **Origin request policy** like this.

- Cache policy

In the cache key settings add the following headers.

Some headers might not be exist in the headers list , So we should add these manually by clicking **Custom**.

aws s3 cors

- Origin Request Policy

In the origin request settings add the following headers.

aws s3 cors

Some headers might not be exist in the headers list , So we should add these manually by clicking **Custom**.

So we created two policies.

And finally we add these two policies to the cache key and origin request section by choosing from the lists.

Conclusion

As you see , we enabled cors for s3 & cloudfront by creating policies for s3 & cloudfront quickly😉.So next step is , we can serve our files from our bucket which is powered by cloudfront so we have ssl and all other benefits comes from cloudfront.

By the way , creating a cdn with Aws services is another subject.Maybe we talk about it in the future posts. Have a nice cors ❗😃