johnpoint

johnpoint

(。・∀・)ノ゙嗨
github

CORS Configuration Memo

Recently, I've been tinkering with the fonts on my blog and have finally settled on a few fonts to use for the website (quite a mouthful).

Now, here's the problem. The font licensing on the Fangzheng website is for non-commercial use only. Even though I'm using it for non-commercial purposes, I decided to separate the fonts from the project to minimize my risk (just in case.jpg).

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

So, I ended up putting the fonts on a resource server called cdn.6-d.cc. I put all my external resources like images on there, and I also put the fonts on https://cdn.6-d.cc/font/. If you open F12 -> network and refresh, you should 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 called a cross-origin request, and it runs into a security policy called Same-origin policy. But don't worry, there's a way to bypass this policy called Cross-origin resource sharing (CORS). This technical specification allows for cross-domain resource calls by adding headers. It can also restrict the scope of resource calls. After all, I don't want to deal with Fangzheng's legal team (running away).

Here's 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 due to the domain restrictions. I don't want to mislead anyone, 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 to 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.