CSS 使用自己的 CDN 嵌入字体无效

CSS font embedding with own CDN not working

我在使用 CSS 嵌入字体时遇到问题。我只有很少的前端经验。现在我要部署我的网站。但在部署之前,我首先将所有资产文件(如 js、css 和字体)上传到我的 CDN 服务器。但我的网站仍在本地主机上。然后我将所有资产 link 更改为我的 cdn link 并在本地主机上访问了我的网站。 CDN 上的所有 javascript 文件都与我的本地网站完美配合。 CSS 文件也可以正常工作,但字体嵌入除外。

I am embedding font like this before I change links to CDN.

@font-face {
    font-family: 'TharLon';
    src: url(../fonts/tharlon.woff) format('woff');
}

.font-class{
    font-family:'TharLon' !important;
}

当所有都在本地主机上时,它工作完美。

Then I changed all links to CDN and embedded font like this

@font-face {
    font-family: 'TharLon';
    src: url('http://d3ewfjbf99d22n.cloudfront.net/assets/fonts/tharlon.woff') format('woff');
}

.font-class{
    font-family:'TharLon' !important;
}

当我这样做时,字体嵌入不是

您的 CORS 似乎有问题。

我刚刚将它添加到 JSFiddle 并且我得到了这个 error:

Font from origin 'https://d3ewfjbf99d22n.cloudfront.net' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://fiddle.jshell.net' is therefore not allowed access.

这很可能是因为 CORS

由于您似乎使用的是 Amazon S3,因此您可以添加所需的 headers,如下所示:

  • 登录您的亚马逊账户。
  • 选择您的 S3 存储桶
  • 单击“编辑 CORS 配置”
  • 添加以下代码并保存所有设置

    <CORSConfiguration>
        <CORSRule>
            <AllowedOrigin>http://www.example1.com</AllowedOrigin>
    
            <AllowedMethod>PUT</AllowedMethod>
            <AllowedMethod>POST</AllowedMethod>
            <AllowedMethod>DELETE</AllowedMethod>
    
            <AllowedHeader>*</AllowedHeader>
        </CORSRule>
    </CORSConfiguration> 
    

发件人:https://www.maxcdn.com/one/tutorial/how-to-use-cdn-with-webfonts/(向下滚动到 S3 存储桶)

在获取端点之前,您必须确保您的 CDN 接受某些浏览器使用的 OPTIONS 方法。

在 CloudFront (AWS) 中,默认仅接受 GET 和 HEAD 方法