Cross-Origin Resource Sharing (CORS)
A cross-origin request occurs when a webpage on one origin (for example, a.example.com) requests a resource from a different origin (for example, b.secondexample.com). Cross-Origin Resource Sharing (CORS) is a mechanism that uses HTTP headers to let the server at b.secondexample.com indicate whether a.example.com is allowed to access its resources. Browsers enforce these headers and block access to responses that are not permitted.
Cloudflare supports CORS by:
- Identifying cached assets based on the
HostHeader,OriginHeader, URL path, and query. This allows different resources to use the sameHostheader but differentOriginheaders. - Passing
Access-Control-Allow-Originheaders from the origin server to the browser.
The Access-Control-Allow-Origin header lets a server specify rules for sharing its resources with external origins. A server may respond with different Access-Control-Allow-Origin values depending on the Origin header in the request. These headers are often present on cacheable content.
If you add or change CORS configuration at your origin web server, purging the Cloudflare cache by URL does not update the CORS headers. Force Cloudflare to retrieve the new CORS headers via one of the following options:
- Change the filename or URL to bypass cache to instruct Cloudflare to retrieve the latest CORS headers.
- Use the single-file purge API to specify the appropriate CORS headers along with the purge request.
- Update the resource’s last-modified time at your origin web server. Then, complete a full purge to retrieve the latest version of your assets including updated CORS headers.
You can use one of following methods to set CORS headers using Cloudflare products:
- Use a Worker: Refer to CORS header proxy for an example.
- Configure a Snippet: Refer to Define CORS headers for an example.
- Use Transform Rules: Refer to Add a wildcard CORS response header for an example.