Font-Face Cross Domain with Nginx

CSS Font-Face 中字体引用外部资源时,  出现错误: “No 'Access-Control-Allow-Origin' header is present on the requested resource”  的解决方案:

问题描述

在页面中使用了字体图标,当通过外部链接(http://google.com/...)引用css文件时会报错,字体不显示.

谷歌调试工具提示:Font from origin 'http://google.com/' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

火狐调试工具提示:已阻止交叉源请求:同源策略不允许读取http://google.com/font_aweso ... ebfont.woff?v=4.0.3 上的远程资源。可以将资源移动到相同的域名上或者启用 CORS 来解决这个问题。

@font-face{
    font-family:'PreloSlab';
    src:url('../fonts/preloslab-medium-webfont.eot');
    src:url('../fonts/preloslab-medium-webfont.eot?#iefix') format('embedded-opentype'),
        url('../fonts/preloslab-medium-webfont.woff') format('woff'),
        url('../fonts/preloslab-medium-webfont.ttf') format('truetype'),
        url('../fonts/preloslab-medium-webfont.svg#PreloSlabMedium') format('svg');
    font-weight:normal;font-style:normal
    }

 解决方案:

1. Nginx 添加配置

location ~* \.(eot|ttf|woff)$ {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}

2. 使用base64引用字体文件

    将字体文件以base64编码的方式引入内嵌到样式文件中。这个本人尝试过,书写格式如下:

@font-face{

src : url("data:application/x-font-ttf;charset=utf-8;base64,XXXXXXXXXXXX") format("ttf");

}

 

 

实际使用过程将那一长串”X“换成自己的base64编码即可。

posted @ 2017-02-08 13:45  宏来  阅读(516)  评论(0编辑  收藏  举报