Font-Awesome 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头

FMa*_*008 2 wordpress .htaccess nginx cors font-awesome

这是对常见问题的新看法。

所以我有一个 Plesk 托管,在通配符域上有 SSL。我有一个 WordPress 主题,它使用 Font-Awesome 图标,托管在同一服务器上。我已将以下几行添加到我的 /httpdocs/.htaccess 文件的最顶部:

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

我使用 Polylang 翻译插件,该插件设置为使用不同语言的子域:

  • mysite.com(英语)
  • fr.mysite.com(法语)

当我访问 example.com 时,一切正常。当我访问 fr.example.com 时,控制台中出现很多以下错误:

Access to font at 'https://example.com/wp-content/plugins/elementor/assets/lib/font-awesome/webfonts/fa-brands-400.woff2' from origin 'https://fr.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Run Code Online (Sandbox Code Playgroud)

我希望通过将标题设置行添加到我的 .htaccess 中来消除错误,但它似乎根本没有帮助。根据 Plesk 的说法,我确实激活了标头模块。

我确实使用 NGINX 作为 Apache 的代理,所有这些都具有默认配置。我确实尝试添加以下几行,以防万一,但所有 3 次尝试都会导致错误 500:

#NGINX < 1.4
 if ($filename ~* ^.*?\.(eot)|(ttf)|(woff)$){
    add_header Access-Control-Allow-Origin *;
 }

# NGINX 1.4
location ~* \.(eot|ttf|woff|woff2)$ {
    add_header Access-Control-Allow-Origin *;
}

# NGINX > 1.6
if ($request_uri ~* ^.*?\.(eot)|(ttf)|(woff)$) {
    add_header Access-Control-Allow-Origin *;
}
Run Code Online (Sandbox Code Playgroud)

我还尝试将其添加到 .htaccess 中,但没有成功:

Header set Access-Control-Allow-Origin "*"
Run Code Online (Sandbox Code Playgroud)

看起来 .htaccess 几乎没有被加载,但重写规则和 WP-Optimize 的缓存标头工作正常并且来自同一文件。

知道我做错了什么吗?

FMa*_*008 7

因为我使用 ApacheNGINX。Apache 的角色是服务更复杂的请求,而 NGINX 的角色是快速服务静态文件。标头代码没有被使用,因为导致错误的特定文件被认为是静态文件,因此由 NGINX 直接提供服务,Apache 永远不会参与其中。

在 Plesk 中,如果您进入域example.com> Apache & nginx Settings,请向下滚动一点并检查 NGINX 设置。(请注意,您需要将此应用于您的主域,而不是子域)

就我而言,我有:

[X] Proxy mode 
[X] Smart static files processing 
[_] Serve static files directly by nginx 
Run Code Online (Sandbox Code Playgroud)

基本上,NGINX 试图变得聪明并提供 ttf、woff、woff2 等服务。这样做时,.htaccess 永远不会解释这些文件。

解决方案

在 Plesk 中,如果您进入域example.com> Apache & nginx Settings. 取消选中Smart static file processing并选中Serve static files directly by NGINX

[X] Proxy mode 
[_] Smart static files processing 
[X] Serve static files directly by nginx 
Run Code Online (Sandbox Code Playgroud)

在最后一个选项下,您有一个文本框,其中预先填充了您希望 NGINX 直接提供服务的文件扩展名。我确保从列表中删除 ttf、woff、woff2。这样,Apache 现在负责提供这些文件的速度稍慢,但它会读取 .htaccess 文件并将其应用到其中。

/httpdocs/.htaccess文件中,我在最顶部有一段代码:

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

现在应该可以了!