What is CORS (Cross Origin Resource Sharing) and How to Configure?Learn the benefits of Cross-Origin Resource Sharing, how to use it in your web development and the dangers of CORS misconfiguration.

In this article, we'll introduce you to cross-origin resource sharing (CORS) and show you how it can be used to improve the performance of your web applications.
Cross-Origin Resource Sharing (CORS) is an essential part of the web development process. It helps to ensure that resources can be shared freely across domains, allowing users access to the content they need while protecting their data's privacy. This guide will provide a comprehensive overview of CORS and detailed instructions for implementation.
What is Cross-Origin Resource Sharing (CORS)
Cross-Origin Resource Sharing (CORS) is a technique used by web browsers to allow elements from one website to be loaded into another without intruding on the privacy of the second. This behaviour can be useful for two reasons - loading scripts from other websites into your own and integrating third-party features into your site without exposing your user's personal data. However, if a website's CORS policy is improperly implemented, it also raises the possibility of cross-domain attacks.
CORS achieves this by establishing a set of rules that govern how cross-domain requests should be handled. It is important to understand these rules before implementing CORS on your website.
How to Implement Cross-Origin Resource Sharing (CORS) in Your Website
When enabling CORS on your web server, creating a custom headers file containing information regarding the resource requests and responses you want to handle as cross-origin requests is important. This includes the Access-Control-Allow-Origin
header, which should contain the list of domains or ports from which cross-domain requests should be allowed. It is important to note that any wildcard (*) entries here will allow access from any domain, so use specific domains or narrow wildcards cautiously. The Access-Control-Allow-Methods
header should be set to specify what types of media can be requested (i.e., GETs and POSTs).
For a successful cross-origin request between two domains, the browser must specify which headers are allowed in the preflight request. This is done by setting the Access-Control-Request-Headers
header to a comma-separated list of header names acceptable in the planned request. If you need certain behaviour from specific domains or URLs, it is important to allow them explicitly using this header instead of general wildcards in Access-Control-Allow-Origin or Access-Control-Allow Methods. Doing so gives you more control over what resources can be accessed from which sources.
Configure your Web Server (Apache/IIS) Correctly
When setting up CORS on a web server, it is important to configure the server correctly. Depending on the type of web server you are using, specific steps may need to be taken to ensure that requests from different domains are allowed access. You will also need to set specific headers to allow/restrict access to certain resources. Once you have configured your web server according to CORS rules, all requests should be respected, and cross-domain requests should return the expected results.
CORS on Apache
Add the following line to the Directory, Location, Files, or VirtualHost sections of your server configuration (often found in a *.conf file, such as httpd.conf or apache.conf), or inside a.htaccess file, to add the CORS authorisation to the header using Apache:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
This will allow any origin site access to the resource. To only allow specific sites to access the resource, the origin domains can be specified in the header using a pipe delimiter.
<IfModule mod_headers.c>
SetEnvIf Origin "http(s)?://(www\.)?(google.com|staging.google.com|development.google.com)$" AccessControlAllowOrigin=$0
Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
</IfModule>
Restarting Apache is required after making changes to configuration files. However, if the .htaccess file is added, there is no need to restart.
CORS on IIS
CORS is configured in ISS via a site or application web.config and has its own CORS configuration section within system.webServer
.
Examples of settings are provided below to enable CORS for a website. The * origin permits all host origins. However, later-included origins that begin with http://* are not. The CORS response is personalised with different CORS configurations as an example for the https://*.example.com
host origin.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<cors enabled="true" failUnlistedOrigins="true">
<add origin="*" />
<add origin="https://*.example.com"
allowCredentials="true"
maxAge="120">
<allowHeaders allowAllRequestedHeaders="true">
<add header="header1" />
<add header="header2" />
</allowHeaders>
<allowMethods>
<add method="DELETE" />
</allowMethods>
<exposeHeaders>
<add header="header1" />
<add header="header2" />
</exposeHeaders>
</add>
<add origin="http://*" allowed="false" />
</cors>
</system.webServer>
</configuration>
CORS in PHP
You can still send the header from a PHP script even if you don't have access to Apache's configuration options. You must include the following in your PHP scripts.
The sample below briefly summarises the HTTP headers that must be specified for CORS to function.
Based on regular expressions, it establishes a list of permitted origin domains. The Origin header given in the client request, which can be found in $_SERVER['HTTP ORIGIN']
, will be compared to this list. The necessary CORS headers will be set if one origin element from the list matches. This configuration also takes care of the CORS preflight request.
$allowedOrigins = array(
'(http(s)://)?(www\.)?example\.com',
'(http(s)://)?(www\.)?demo\.com'
);
if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] != '') {
foreach ($allowedOrigins as $allowedOrigin) {
if (preg_match('#' . $allowedOrigin . '#', $_SERVER['HTTP_ORIGIN'])) {
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
break;
}
}
}
Build an authentication system so secured requests are handled properly
Implementing a secure authentication system is essential for proper cross-origin resource sharing. This ensures the requests between two domains are properly authenticated and authorised, preventing malicious actors from accessing sensitive data through CORS exploits. When setting up your authentication system, it is important to ensure the requests are carried out over HTTPS or other authenticated protocols. You should also use trusted third-party services like OAuth2 and OpenID Connect to authenticate users securely.
What Is A CORS Error and How to Fix It
If you've ever tried to make a cross-origin request from your browser, you've probably encountered a CORS error. CORS errors occur when your browser cannot request another domain due to the same-origin policy. The same-origin policy is a security measure that prevents Javascript from making requests to domains other than the one it's currently on.

Fortunately, there are a few ways to work around CORS errors.
Typically, an error notice will appear. CORS policy on the browser console, followed by a reason like one of the following, has prohibited access to XMLHttpRequest.
- No 'Access-Control-Allow-Origin' header present.
- No 'Access-Control-Allow-Headers' headers present.
- Method not supported under 'Access-Control-Allow-Methods' header.
- Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is on the requested resource.
A CORS error happens when the server fails to return the necessary CORS headers.
Errors are usually due to the browser not sending the HTTP_ORIGIN header or the HTTP_ORIGIN header not correctly specifying the hostname. The error is also seen when the server does not specify the correct header in the allowed origin.
For instance, https://example.com tries to access resources on https://demo.com using an API request that is denied. The browser will show a CORS error since the response's Access-Control-Allow-Origin header does not include https://example.com.