In this blog post , We will learn to configure cross domain resource sharing in S3 bucket

What is CORS?

Cross-origin resource sharing (CORS) defines a way for client web applications that are loaded in one domain to interact with resources in a different domain. With CORS support, you can build rich client-side web applications with Amazon S3 and selectively allow cross-origin access to your Amazon S3 resources.

How CORS works?

You are hosting a static website using S3 bucket and the end users can access the website using S3 endpoint.

For instance, If you want to use javascript files on the web page from your S3 bucket to be able to make authenticated GET and PUT requests against the same S3 bucket by using the S3 endpoint.

Normally, browsers wont allow javascript files for GET and PUT methods, so In this case we should allow CORS in the bucket so that your S3 endpoints can be able to make those requests.

Allowed Methods:

In the CORS configuration, You can specify the following methods for the element.

  • GET
  • POST
  • PUT
  • HEAD
  • DELETE

Adding CORS configuration to S3 Bucket:

To configure your bucket to allow cross-origin requests, you add CORS configuration to the S3 bucket.

A CORS configuration is an XML document that defines rules that identify the origins that you will allow to access your bucket, the operations (HTTP methods) supported for each origin, and other operation-specific information.

Sign in to AWS Management console and Open S3 Console,

https://console.aws.amazon.com/s3/

In the lists of S3 buckets, Choose the bucket name for which you want to enable CORS.

S3 Bucket

Choose Permissions and then select CORS configuration.

S3 Bucket

In the CORS configuration editor text box, Type the CORS configuration , The CORS should be a valid XML format.

Add the below code to allow CORS from any source / origin. * represents that it allow CORS for all source /origin.

S3 Bucket
If you want to allow CORS for a particular domain , Add the below Configuration.

S3 Bucket

Things to Note:

  • If a user send a request via http , the website wont be accepted because we have allowed only https.It always suggested to redirect all the http request to https.
  • Another case is with www and non-www domains.If a request comes from non-www domains and if we havn’t allowed CORS for non-www domains , the request will be failed, But this can be fixed by added an addition rule to CORS configuration as shown below,
  • We just need to add one more .

S3 Bucket

Hope It helps, Thanks for reading this article.

Please do check out my other articles.