Recently, due to the business requirements of a client website, the website needs to deploy a multi-language plugin, which uses a subdomain approach, resulting in cross-origin issues when calling font files. On the other hand, some of the website's users who previously used the niRvana theme developed by a domestic author encountered issues with the Slider Revolution plugin. OSS Due to object storage, some JS 文件调用时,同样出现了类似: CORS:No ‘Access-Control-Allow-Origin’ header Cross-domain issues. So, today we're going to talk about how to solve this problem.
Actually, we encounter issues when using cross-domain calls to resources. CORS:No ‘Access-Control-Allow-Origin’ header This type of question means: The request's resource is blocked by CORS strategy, and there is noAccess-Control-Allow-OriginHeader. This is causing our site's other domain resources called from other domains to fail to load and display normally.
解决办法
由于 Access-Control-Allow-Origin * Cross-domain is extremely dangerous, therefore we need to constrain specific file types when selecting the rules for cross-domain calls. For example, font files require cross-domain, so we only need to configure font file cross-domain.
Apache Access-Control-Allow-Origin font跨域配置
We need to add the following code to the .htaccess file: <IfModule mod_rewrite.c> <IfModule mod_headers.c> <FilesMatch "\.(css|js)$"> Header set Access-Control-Allow-Origin "*" </FilesMatch> </IfModule> </IfModule> Note: The above code is in American English and is a direct translation of the Simplified Chinese text.
Header set Access-Control-Allow-Origin "*"
This can be achieved by enabling cross-origin resource sharing (CORS) in the Apache environment for font files, which allows requests to be made from a different origin (domain, protocol, or port) than the one the font files are hosted on.
Here is the translated text in American English:
This can be achieved by enabling cross-origin resource sharing (CORS) in the Apache environment for font files, which allows requests to be made from a different origin (domain, protocol, or port) than the one the font files are hosted on.Header set Access-Control-Allow-Origin --Specify allowed URLs;。
Nginx 中 Access-Control-Allow-Origin 字体跨域配置
我们需要配置 nginx.conf 文件,加入如下代码:
location ~* \.(ttf|ttc|otf|eot|svg|woff|woff2)$ {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
}
这样就可以实现在 Nginx 环境下 GET,POST,OPTIONS 的跨域请求支持,同样也可以add_header Access-Control-Allow-Origin --指定允许的 url;。
注意:如果想要支持跨域调用 JS 文件,就需要将 JS 的文件类型加入允许的文件类型中;修改完网页服务器配置文件后,要记得重启网页服务器服务。