Reason: CORS header ‘Access-Control-Allow-Origin’ missing

By bhagwatchouhan
Reason: CORS header ‘Access-Control-Allow-Origin’ missing

Sometimes the browser does not load the static resources including images, fonts or requests triggered for the domain which is not the same as that of the website. In such a case, we can directly open the browser console and observe the missing resources. The browser will show the CORS error for missing resources as shown in Fig 1.

CORS Error

Fig 1

We can resolve this error by updating the web server configuration specific to the website showing these errors.

Origin

The word origin is referred to as the source server serving the request. In case the page HTML is using resources from multiple origins, we need to allow the main origin to access another origin resource in case the browser throws CORS error messages on the console.

Apache

Update the website record(VirtualHost) or .htaccess file as shown below.

# Allow all the CORS requests
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>

# Use it directly bypassing the check for header module
Header set Access-Control-Allow-Origin "*"


# Preferred way - Use it only for known servers by providing correct url
Header set Access-Control-Allow-Origin "<server url>"

We can also allow selected files as shown below.

# Allow fonts from any Origin
<FilesMatch ".(eot|ttf|otf|woff)">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>

# Allow static resources from a specific CDN
<FilesMatch ".(jpeg|jpg|png|gif|css|js)">
Header set Access-Control-Allow-Origin "<CDN Path>"
</FilesMatch>

Nginx

Update the website config as shown below.

# Allow all the CORS requests
add_header Access-Control-Allow-Origin *;

# Preferred way - Use it only for known servers by providing correct url
add_header Access-Control-Allow-Origin <server url>;

share on :

Profile picture for user bhagwatchouhan
bhagwatchouhan