Overview
Cross Origin Resource Sharing (CORS) allows restricted resources on a website to be requested from another domain outside the domain from which it was originally served.
This example explains how this works:
- Site A adds CORS headers to allow site B access to a resource on site A, such as a font.
- Site B can then access that resource due to the CORS header.
Without the CORS header, Site B would not be able to access the resource on Site A. View the following pages for further details.
Only certain requests use CORS
The following requests use CORS.
- Invocations of the
XMLHttpRequest
or Fetch APIs. - Web Fonts (for cross-domain font usage in
@font-face
within CSS). - WebGL textures.
- Images/video frames drawn to a canvas using
drawImage()
. - CSS Shapes from images.
What does this mean?
This means that requests to files such as index.html will not use CORS. However, a request to a font or CSS file will use CORS.
Where to add CORS headers
CORS headers are added to an .htaccess file in your site's main directory. View the following article for further details.
Adding CORS headers
The following links explain CORS headers in more detail.
- Access-Control-Allow-Headers
- CORS Tutorial: A Guide to Cross-Origin Resource Sharing
- developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
- developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
- developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
The following are two simple examples of how to add CORS headers to your site.
Wildcard values
This example uses wildcards for each CORS header:
Header add Access-Control-Allow-Origin: "*" Header add Access-Control-Allow-Methods: "*" Header add Access-Control-Allow-Headers: "*"
Specific values
This example uses specific values for each CORS header:
Header add Access-Control-Allow-Origin: "https://example.com" Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT" Header add Access-Control-Allow-Headers: "Upgrade-Insecure-Requests"
Testing CORS headers
You can run the curl command (via SSH) to verify your CORS headers are functioning.
Make sure the URL you enter is to a specific asset on your site. The example below is checking the site's style.css file.
If you just check the index.html page, CORS headers will not be returned.
[server]$ curl -I https://example.com/style.css HTTP/1.1 200 OK Date: Fri, 29 Mar 2024 20:06:59 GMT Server: Apache Upgrade: h2 Connection: Upgrade Last-Modified: Tue, 26 Mar 2024 21:53:08 GMT ETag: "2d-598e7d69349fd" Accept-Ranges: bytes Content-Length: 45 Access-Control-Allow-Origin: https://example.com Access-Control-Allow-Methods: DELETE,PUT,OPTIONS,DELETE,PUT Access-Control-Allow-Headers: Upgrade-Insecure-Requests Content-Type: text/css