Access to fetch at ‘https://example.com’ from origin ‘https://example2.com’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

Does this error look familiar? This usually happens when a client browser is trying to access a resource from another domain via client script (typically javascript). Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served.

Solution via NGINX webserver: Add a header directive that tells the browser that this origin is whitelisted to access the resource

If you are accessing the resource from a domain that you own, then you are in luck. You can tell your webserver to allow your other domain to have access. Add the following code in your NGINX conf file. This can be placed within the server block.

add_header 'Access-Control-Allow-Origin' "${scheme}://definedictionarymeaning.com" always;

Explanation: If resource is hosted on craftypixels.com then we are telling its webserver that when a client requests a resource from definedictionarymeaning.com then allow it.

How to add multiple origin headers?

Adding multiple add_header is simple. In following code needs to be placed in the location block inside the server block. Replace the site1.com with the sites you want to whitelist.

  if ($http_origin ~* "^https?://(site1.com|site2.com|site3.com)$") {
            add_header Access-Control-Allow-Origin "$http_origin";
        }

Why does CORS exists?

CORS exists to protect the internet from evil hackers and intruders. For many years a script from one site could not access the content of another site. That simple, yet powerful rule was a foundation of the internet security. E.g. an evil script from website badsite.com could not access the user’s mailbox at website gmail.com. JavaScript also didn’t have any special methods to perform network requests at that time. It was a toy language to decorate a web page.

This article tries to address following errors:

  1. cors policy no access control allow origin
  2. cross origin request blocked
  3. blocked by cors policy
  4. access blocked by cors policy
  5. cors header access control allow origin missing
  6. no access control allow origin header is present