This article guides you on how to resolve Cross-Origin Resource Sharing (CORS) errors when using our Amazon S3 Integration plugin.
We will walk you through the following sections:
- What is a CORS?
- Why do you need CORS?
- How to configure CORS on Amazon S3 Bucket?
- How to enable CORS on your Server?
What is a CORS?
When requesting a resource (asset) such as a FontAwesome font or a jQuery script not hosted our website server (origin), you’re in fact making a cross-origin request.
Cross-Origin Resource Sharing (CORS) manages cross-origin requests and allows web application running at a particular domain to access resources hosted in other different domains.
Why do you need CORS?
CORS is necessary as it allows you to set not only who can access the assets hosted on your server, but also how these assets can be accessed.
For example, you may want other websites (external origins) to read but not edit or delete your assets. You can do so with CORS by specifying which HTTP request methods, e.g. GET, DELETE, PUT
, are allowed from external origins.
In case of Amazon S3 and CloudFront CDN, your website actually makes cross-origin requests from your website or CloudFront domain to media files hosted on Amazon S3 bucket. So in order for Amazon S3 to serve these file requests, you need to update the CORS configuration for the Amazon S3 bucket as described below.
How to configure CORS on Amazon S3 Bucket?
First of all, log into your AWS account and go to S3 dashboard.
Next, go to your S3 bucket and switch to the Permission tab.
Navigate to the bottom of the page, you will see the Cross-origin resource sharing (CORS) option. Simply click on “Edit” button to add the new rules.
[ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "HEAD" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ]
* refers to all external domains. Alternatively, you can specify a particular domain (http://example.com) instead.
How to enable CORS on your Server?
In contrast to your media files hosted on Amazon S3, your website assets such as JS, CSS and TTF files are still hosted on your website server (origin). So any CloudFront requests to these assets need permissions from the origin (your server). Here’s how you can enable CORS on your server:
Apache servers
Put the following rules on your .htaccess
<IfModule mod_headers.c> <FilesMatch "\.(ttf|ttc|otf|eot|woff|font.css|css|js)$"> Header set Access-Control-Allow-Origin "*" </FilesMatch> </IfModule>
NGINX servers
Place the following codes within the curly braces in the server { … } block of your configuration located under /etc/nginx/sites-enabled/
location ~* \.(eot|svg|ttf|woff|woff2|json)$ { add_header 'Access-Control-Allow-Origin' *; }