🤖 正在生成内容...

一、核心原理

自建字体CDN的核心是通过跨域资源共享(CORS) + CDN缓存加速 + 自定义域名来提供字体服务。

二、设置niginx伪静态

由于浏览器对字体文件有严格的跨域限制,必须配置正确的CORS头:

# 宝塔面板 → 网站 → 设置 → 伪静态
# 粘贴以下完整配置:

location ~* \.(woff2|woff|ttf|eot|otf)$ {
    # 1. CORS头(必须)
    add_header Access-Control-Allow-Origin "*" always;
    add_header Access-Control-Allow-Methods "GET, OPTIONS" always;
    
    # 2. 处理OPTIONS预检请求
    if ($request_method = 'OPTIONS') {
        add_header Access-Control-Allow-Origin "*";
        add_header Access-Control-Allow-Methods "GET, OPTIONS";
        add_header Access-Control-Allow-Headers "Origin, Accept, Content-Type";
        add_header Access-Control-Max-Age 86400;
        add_header Content-Length 0;
        add_header Content-Type "text/plain; charset=UTF-8";
        return 204;
    }
    
    # 3. 缓存配置(重要)
    expires max;
    add_header Cache-Control "public, immutable, max-age=31536000" always;
    
    # 4. 防止被覆盖的安全头
    add_header Vary Origin always;
    
    # 5. 确保字体正确识别
    types {
        font/woff2 woff2;
        font/woff woff;
        application/x-font-ttf ttf;
        application/vnd.ms-fontobject eot;
    }
}

伪静态设置完成后即可通过url引入字体