如何添加 Access-Control-Allow-Origin 标头 [英] How to add an Access-Control-Allow-Origin header

查看:43
本文介绍了如何添加 Access-Control-Allow-Origin 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计一个网站(例如 mywebsite.com),该网站从另一个网站(例如 anothersite.com)加载字体字体.我在 Firefox 中加载字体时遇到问题,我阅读了 这个博客:

I am designing a website (e.g. mywebsite.com) and this site loads font-face fonts from another site (say anothersite.com). I was having problems with the font face font loading in Firefox and I read on this blog:

Firefox(支持@font-face从 v3.5) 不允许跨域默认字体.这意味着字体必须从同一个域提供(和子域),除非您可以添加访问控制允许来源"标题到字体.

Firefox (which supports @font-face from v3.5) does not allow cross-domain fonts by default. This means the font must be served up from the same domain (and sub-domain) unless you can add an "Access-Control-Allow-Origin" header to the font.

如何将 Access-Control-Allow-Origin 标头设置为字体?

How can I set the Access-Control-Allow-Origin header to the font?

推荐答案

所以你要做的是... 在字体文件文件夹中放置一个 htaccess 文件,其中包含以下内容.

So what you do is... In the font files folder put an htaccess file with the following in it.

<FilesMatch ".(ttf|otf|eot|woff|woff2)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
  </IfModule>
</FilesMatch>

同样在您的远程 CSS 文件中,font-face 声明需要字体文件的完整绝对 URL(在本地 CSS 文件中不需要):

also in your remote CSS file, the font-face declaration needs the full absolute URL of the font-file (not needed in local CSS files):

例如

@font-face {
    font-family: 'LeagueGothicRegular';
    src: url('http://www.example.com/css/fonts/League_Gothic.eot?') format('eot'),
         url('http://www.example.com/css/fonts/League_Gothic.woff') format('woff'),
         url('http://www.example.com/css/fonts/League_Gothic.ttf') format('truetype'),
         url('http://www.example.com/css/fonts/League_Gothic.svg')

}

这将解决问题.需要注意的一件事是,您可以准确指定应允许哪些域访问您的字体.在上面的 htaccess 中,我已经指定每个人都可以使用 "*" 访问我的字体,但是您可以将其限制为:

That will fix the issue. One thing to note is that you can specify exactly which domains should be allowed to access your font. In the above htaccess I have specified that everyone can access my font with "*" however you can limit it to:

单个网址:

标头集 Access-Control-Allow-Origin http://example.com

Header set Access-Control-Allow-Origin http://example.com

或以逗号分隔的 URL 列表

Access-Control-Allow-Origin:http://site1.com,http://site2.com

(当前实现不支持多个值)

(Multiple values are not supported in current implementations)

这篇关于如何添加 Access-Control-Allow-Origin 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆