← ServerPilot Docs

How to 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.

How to Enable CORS on Your Apps

You can enable sending CORS headers from your app by adding the following in a .htaccess file in your app's web root directory (public):

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 "*"

Note that trusting all domains can be extremely dangerous to your users if your app wasn't designed for this purpose.

You can learn more about CORS and find detailed examples in the CORS documentation from Mozilla.

How to Enable CORS on File Storage Services

If your app is making requests to a file storage service you use to host static files and you need to enable CORS at that service, you should follow the instructions from your file storage service provider.

Launch your first site in 5 minutes