johnpoint

johnpoint

(。・∀・)ノ゙嗨
github

CORS Configuration Notes

Recently, I have been tinkering with the fonts on my blog and have finally chosen these fonts as the website's fonts (a bit tongue-twisting):

Now, here comes the problem. The font authorization obtained from Fangzheng's website is for non-commercial use. Even though I am using it for non-commercial purposes, I still decided to separate the fonts from the project to reduce my risk (fear of death.jpg).

Hmm, how can I use the fonts if I don't include them in the theme? It's unlikely that font CDNs online will have Fangzheng's fonts...

In the end, I put the fonts on a resource server called cdn.6-d.cc. I put all my external resources like images on there, and I put the fonts on https://cdn.6-d.cc/font/. If you open F12->network and refresh the page, you should be able to see two resources with the .ttf extension being loaded from cdn.6-d.cc.

Configuring CORS#

Things are not that simple when it comes to referencing from another domain. It's a type of request called cross-origin request (a bit tongue-twisting x2). However, this type of request will encounter a security policy called Same-origin policy in browsers. The good news is that there is a corresponding method to bypass this policy called Cross-origin resource sharing (CORS). This technical specification allows cross-domain calls to resources by adding headers. By the way, it can also restrict the scope of resource calls. After all, I don't want to run into Fangzheng's legal team (run away).

Here is the specific configuration:

location /font {
    set $cors_origin "";
    if ($http_origin ~* "^https://blog.lvcshu.com$") {
            set $cors_origin $http_origin;
    }
    if ($http_origin ~* "^https://johnpoint.github.io$") {
            set $cors_origin $http_origin;
    }
    if ($http_origin ~* "^https://lvcshu.netlify.com$") {
            set $cors_origin $http_origin;
    }
    if ($request_method = 'OPTIONS') {
    return 204;
    }
    add_header Access-Control-Allow-Origin $cors_origin always;
    add_header Access-Control-Allow-Headers "Content-Type, Authorization" always;
    add_header Access-Control-Allow-Methods "GET, POST, OPTIONS, PUT, PATCH, DELETE, HEAD" always;
    add_header Access-Control-Max-Age 86400 always;
}

Modifying CSS#

However, if I hardcode my URL in the project's CSS, it won't work because of the domain restrictions above. I can't mislead others like that, QAQ. So I removed the font declarations in the project's CSS. To correctly load the fonts, all you need to do is add this line in all.css:

@font-face{font-family:"FZJL";src:url('font-url')}
@font-face{font-family:"FZLT";src: url('font-url')}

and it will take effect.

References#

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.