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

时间:2021-01-24 00:07:27

标签: 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>

我使用 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.

我希望通过将 Header set 行添加到我的 .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 *;
}

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

Header set Access-Control-Allow-Origin "*"

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

知道我做错了什么吗?

1 个答案:

答案 0 :(得分:1)

因为我使用 Apache NGINX。 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 

基本上 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 

在最后一个选项下,您有一个文本框,其中预先填充了您希望 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>

现在它应该可以工作了!