Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

In many cases, large and medium-sized websites put static resources (such as font files and images) on independent servers or CDN and use independent resource domain names (such as res.test.com) in order to distribute static resources, speed up access and reduce the pressure on the main site.

In actual deployment, however, you will find that the browser cannot load these resources with different domain names, and the Firefox console will report an error:

[html] view plain copy

  1. Cross-source requests blocked: The same-origin policy forbids reading of remote resources at http://xxxxx. (Cause: CORS header lacks’ access-Control-allow-origin ‘).
  2. Cross-source requests blocked: The same-origin policy forbids reading of remote resources at http://xxxxx. (Cause: CORS request failed).

This is because modern browsers define them as cross-domain resources and do not allow them to be loaded

To understand cross-domain, you must first understand the same-origin policy. The same origin policy is a very important security policy implemented in browsers for security purposes. A URL consists of the protocol, domain name, port, and path. If the protocol, domain name, and port of two urls are the same, they are of the same origin. Same origin policy: The browser’s same origin policy, which restricts “document” or scripts from different sources from reading or setting certain properties on the current “document”. (White Hat on Web security [1]) Scripts loaded from one domain do not allow access to document properties in another domain.

The solution is as simple as adding a header to the static resource server:

Access-Control-Allow-Origin *

This article on Apache operations, nginx is much the same

Start by editing httpd.conf

Find the line

#LoadModule headers_module modules/mod_headers.so

Remove the # comment

LoadModule headers_module modules/mod_headers.so

The purpose is to enable the Apache header custom module

Then add a line to the virtual host of the independent resource domain name

Header set Access-Control-Allow-Origin *

Add a header when accessing resources in this domain

Restart the apache

Access again, OK!

NameVirtualHost 10.0.0.2:80 < VirtualHost 10.0.0.2:80 > DocumentRoot ServerName/var/www/host.example.com host.example.com  JkMount /webapp/* jkworker Header set Access-Control-Allow-Origin "*" RewriteEngine on RewriteRule ^/otherhost http://otherhost.example.com/webapp [R,L] </VirtualHost>Copy the code

And here’s an example of the Apache config for the second:

NameVirtualHost 10.0.1.2:80 < VirtualHost 10.0.1.2:80 > DocumentRoot ServerName/var/www/otherhost.example.com otherhost.example.com JkMount /webapp/* jkworker Header set Access-Control-Allow-Origin "*" </VirtualHost>Copy the code

Buy me a cup of coffee 🙂