Enable Cross-Origin Resource Sharing (CORS)
By default, web browsers do not allow websites to make cross-origin requests in certain security-sensitive situations. To tell browsers to allow cross-origin requests to a site that belongs to you, you can use cross-origin resource sharing (CORS).
Note that CORS only works for allowing requests to a site you control. Enabling CORS on a site that is making requests will not fix any problems you may have with browsers blocking cross-origin requests.
What are cross-origin requests?
Cross-origin requests, also known as cross-site requests, occur when a web page on one domain makes requests to URLs on a different domain.
Cross-origin requests are very common and in most cases work by default
in browsers. For example, a domain, example.com
, may include images,
style sheets, and JavaScript files from a different domain, such as
google.com
.
However, some cross-origin requests are blocked by browsers by default because, if they were allowed, they would pose a major security risk to every person using a web browser.
What resources are restricted?
Browsers disallow the following cross-domain resources by default:
- Requests performed with
XMLHttpRequest
- Web fonts
- WebGL textures
- Images drawn to a canvas using
drawImage()
To understand how XMLHttpRequest
would be dangerous if cross-origin
requests were allowed, imagine if you visited a site at evil.com
that
used XMLHttpRequest
to make requests to gmail.com
. If you were
logged into Gmail in your browser, evil.com
would be able to read all
of your email. This example shows why it is the site that receives the
request that must indicate when cross-origin XMLHttpRequest
is
allowed. If the requesting site could bypass the browser’s restriction,
malicious websites could access any site you were logged into.
Enable CORS on an app
You can enable sending CORS response headers from your app by adding the
following to a
.htaccess
file
in your app’s web root directory:
Header always set Access-Control-Allow-Origin "https://example.com"
The above example tells browsers that requests originating from web
pages at https://example.com
should be trusted for accessing your app.
To trust requests from all domains, you would use this:
Header always set Access-Control-Allow-Origin "*"
You can learn more about CORS and find detailed examples in the CORS documentation from Mozilla.
Enable CORS on cloud storage buckets
If your site loads resources from cloud object storage, you should follow the instructions from your cloud provider to enable CORS headers in responses from object storage.