Sign In
Sign In
Updated on 22 November 2024

When using files from S3 buckets on external resources, such as a website, you might encounter a CORS (Cross-Origin Resource Sharing) error. This error occurs when the browser blocks cross-origin requests to your bucket’s resources.

To resolve this issue, you need to configure specific CORS rules for the bucket to allow cross-origin requests. Here's how to set up CORS for an S3 bucket using the AWS CLI utility.

Creating a CORS Rules File

First, create a cors.json file with the desired CORS configuration. This file will allow GET and HEAD requests to objects in your bucket. Here's an example:

{
  "CORSRules": [
    {
      "AllowedHeaders": ["*"],
      "AllowedMethods": ["GET", "HEAD"],
      "AllowedOrigins": ["*"]
    }
  ]
}
  • AllowedMethods: Specifies the HTTP methods allowed. In this example, GET and HEAD requests are permitted.

  • AllowedOrigins: * means requests are allowed from any domain. To restrict access to a specific domain, replace the asterisk with the domain name. For example, if your website is hosted at https://example.com, replace the line with:

"AllowedOrigins": ["https://example.com"]

Uploading CORS Rules to the Bucket

After creating the CORS rules file, upload it to your S3 bucket using the following command:

aws s3api put-bucket-cors --bucket <bucket_name> --endpoint-url https://s3.hostman.com --cors-configuration file://cors.json

Replace <bucket_name> with the name of your bucket.

Verifying CORS Rules

To confirm that the CORS rules have been successfully applied, use this command:

aws s3api get-bucket-cors --bucket <bucket_name> --endpoint-url https://s3.hostman.com

Deleting CORS Rules

If you need to remove the current CORS rules, execute the following command:

aws s3api delete-bucket-cors --bucket <bucket_name> --endpoint-url https://s3.hostman.com

This command will delete all existing CORS rules for the bucket.

Was this page helpful?
Updated on 22 November 2024

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support