How to fix Access-Control-Allow-Origin (CORS origin) Issue

In this post im sharing a working guide for the fix for famous error Access-Control-Allow-Origin (CORS origin) issue for your HTTPS enables either for framework or WordPress website.

You may also like: How to Highlight Text in WordPress Posts

Recently we have worked for our company website running Laravel 5.6 as framework. We added a subdomain for serving assets through that domain. Once all setup completed everything was okay except this CORS issue. It was a big headache and after 2 days of research we were able to fix it. So here we are writing the issue caused to us.

There were commonly 3 types of issues you may notice

No ‘Access-Control-Allow-Origin’ header is present

The ‘Access-Control-Allow-Origin’ header has a value ” that is not equal to the supplied origin.

The ‘Access-Control-Allow-Origin’ header contains multiple values

what is Cross-origin resource sharing (CORS)?

CORS is industry standard for accessing web resources on different domains. It acts as a security measure implemented by web browsers to prevent CSS and Javascript making request against different origin other than its main origin.

Let’s consider this

You have with you

You added with your or link external domain contents with your domain

If have a policy to accept request like CSS or JavaScript from only and ignore all requests from other domains, then your browser’s request will fail with an error.

How did I fix this error?

Just changing Origin URL from http to https may issue solve in some cases or use the below to solve the font loading problem.

<IfModule mod_headers.c>
  <FilesMatch "\.(ttf|ttc|otf|eot|woff|woff2|font.css|css|js)$">
    Header set Access-Control-Allow-Origin "*"

As you see Access-Control-Allow-Origin "*" allows you to access all resources and webfonts from all domains.

Loading assets from Sub-domain

If you are loading your web assets via sub domain then the scenario might be different from above.

Just add below lines to .htaccess file and we should be good.

<ifmodule mod_headers.c>
   SetEnvIf Origin "^(.*\.domain\.com)$" ORIGIN_SUB_DOMAIN=$1
   Header set Access-Control-Allow-Origin "%{ORIGIN_SUB_DOMAIN}e" env=ORIGIN_SUB_DOMAIN
   Header set Access-Control-Allow-Methods: "*"
   Header set Access-Control-Allow-Headers: "Origin, X-Requested-With, Content-Type, Accept, Authorization"


Hope this article helps you to evacuate from the Access-Control-Allow-Origin error completely.

Follow TechBiriyani on FacebookTwitter to get all the latest updates.

Leave a Reply

Your email address will not be published. Required fields are marked *