Font files are blocked by CORS policy

有些话、适合烂在心里 提交于 2019-12-11 15:24:13

问题


I want to build a server accelerated by a CDN provider, which serves static files for my other websites. I decide to use https://www.funfun.org.cn, then for example https://www.funfun.org.cn/libs/font-awesome.min.css and https://www.funfun.org.cn/libs/octicons.min.css should be able to be used by other websites.

However, when I test this server by my website in localhost, I see the following errors:

For example,

Access to Font at 'https://www.funfun.org.cn/libs/octicons.woff' from origin 'https://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:3000' is therefore not allowed access.

Other errors are similar and for https://www.funfun.org.cn/fonts/fontawesome-webfont.woff2?v=4.4.0 and https://www.funfun.org.cn/libs/octicons.ttf, etc.

In my website, those above files are not called directly, I only have the following two lines regarding fonts, which must have called the .ttf and .woff2, etc.

<link rel="stylesheet" href="https://www.funfun.org.cn/libs/font-awesome.min.css"> 
<link rel="stylesheet" href="https://www.funfun.org.cn/libs/octicons.min.css">

So, does anyone know what I can do to fix those errors?

PS: my nginx configuration file is as follows, and all the files are under /var/www/html/libs/ and /var/www/html/fonts/.

server {
    listen 443 ssl;

    ssl_certificate /etc/nginx/cert/1530490648293.pem;
    ssl_certificate_key /etc/nginx/cert/1530490648293.key;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_dhparam /etc/ssl/certs/dhparam.pem;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_session_timeout 1d;
    ssl_stapling on;
    ssl_stapling_verify on;
    add_header Strict-Transport-Security max-age=15768000;

    root /var/www/html;

    server_name funfun.org.cn www.funfun.org.cn;

    location / {
        try_files $uri $uri/ =404;
    }
}

回答1:


Try adding this into your configuration:

location ~* \.(eot|otf|ttf|woff|woff2)$ {
    add_header Access-Control-Allow-Origin *;
    expires max;
}


location / {
    try_files $uri $uri/ =404;
}

Also you may need to update the nginx mine.types file with something like:

application/x-font-ttf           ttc ttf;
application/x-font-otf           otf;
application/font-woff            woff;
application/font-woff2           woff2;
application/vnd.ms-fontobject    eot;


来源:https://stackoverflow.com/questions/51132558/font-files-are-blocked-by-cors-policy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!