Enabling cross-origin resource sharing (CORS)
Last updated 2021-02-23
Enabling Cross-Origin Resource Sharing (CORS) allows a server to indicate that other origins can request sub-resources, like scripts and stylesheets, from it. These origins might use a different scheme (HTTP vs HTTPS) or an entirely different domain or port. This guide describes how to add an Access-Control-Allow-Origin
header, which is sufficient for simple scenarios, and is often useful when using static bucket providers like Amazon S3 and Google Cloud Storage as an origin.
IMPORTANT
We recommend only enabling CORS when you have sub-resources on your server that you want other origins to load, especially if you allow requesting code from any origin, as it makes things less secure.
To enable CORS, set up a custom HTTP header for your service by following the steps below.
- Log in to the Fastly web interface.
- From the Home page, select the appropriate service. You can use the search box to search by ID, name, or domain.
- Click the Edit configuration button and then select the option to clone the active version. The Domains page appears.
- Click the Content link. The Content page appears.
Click the Create header button. The Create a header page appears.
Fill out the Create a header fields as follows:
- In the Name field, enter a descriptive name for the new header (e.g.,
CORS S3 Allow
). This name is displayed in the Fastly web interface. - From the Type menu, select Cache, and from the Action menu, select Set.
- In the Destination field, enter
http.Access-Control-Allow-Origin
. - In the Source field, enter
"*"
to allow requesting code from any origin or specify a single origin location (https://example.com
). If specifying an origin, ensure CORS rules are applied invcl_deliver
. - Leave the Ignore if set menu and the Priority field set to their default values.
- In the Name field, enter a descriptive name for the new header (e.g.,
Click the Create button. The new header appears on the Content page.
- Click the Activate button to deploy your configuration changes.
IMPORTANT
Objects already cached won't have this header applied until you purge them.
Test it out
Running the command:
$ curl -I example.tld/path/to/resource
should include similar information to the following in your header:
1Access-Control-Allow-Origin: http://example.tld2Access-Control-Allow-Methods: GET3Access-Control-Expose-Headers: Content-Length, Connection, Date...
TIP
Access-Control-Allow-Methods
and Access-Control-Expose-Headers
are examples of additional headers you can add with CORS. For more information about these headers, see MDN Web Docs.
Do not use this form to send sensitive information. If you need assistance, contact support.