PSA: Self-hosted web fonts and HTTP vs. HTTPS

Status
Not open for further replies.

Lord Pachelbel

Ars Praefectus
5,499
Subscriptor++
So... if you load a page over HTTP that has stylesheet @font-face rules that load fonts from absolute URLs over HTTPS, the fonts won't render. I discovered this after 45 minutes of troubleshooting broken fonts, and I determined that using the protocol-relative URL everywhere seems to fix it:

DO THIS
Code:
<link rel="stylesheet" href="//www.example.com/css/main.css" />

NOT THIS
Code:
<link rel="stylesheet" href="https://www.example.com/css/main.css" />

DO THIS
Code:
@font-face {
  font-family: 'example';
  src: url(/html//civis/threads/psa-self-hosted-web-fonts-and-http-vs-https.1380063/latest/'https://www.example.com/fonts/example.eot');
  /* ...and so on for the other font formats.. */
}

NOT THIS
Code:
@font-face {
  font-family: 'example';
  src: url(/html//civis/threads/psa-self-hosted-web-fonts-and-http-vs-https.1380063/latest/'https:https://www.example.com/fonts/example.eot');
  /* ...and so on for the other font formats.. */
}
 

Lord Pachelbel

Ars Praefectus
5,499
Subscriptor++
I should mention that if everything is hosted at the same domain, then using normal relative URLs is fine*:

Code:
<link rel="stylesheet" href="/css/main.css" />

@font-face {
  font-family: 'example';
  src: url(/html//civis/threads/psa-self-hosted-web-fonts-and-http-vs-https.1380063/latest/'/fonts/example.eot');
  /* ...and so on for the other font formats.. */
}

My use case was a bit obscure, and I think it triggered something involving the same-origin policy. It's also unusual that I had to self-host my fonts in the first place, because normally I'd use Google Fonts, Typekit, MyFonts, etc. I imagine that this issue comes up more often in the case of custom icon fonts being hosted on a CDN.

Also, setting an Access Control header might also have fixed my problem, but I didn't think about server-side solutions until recently:

Code:
<Directory "/home/example/public_html/fonts">
  <FilesMatch "\.(ttf|otf|eot|woff)$">
    <IfModule mod_headers.c>
      Header set Access-Control-Allow-Origin "*"
    </IfModule>
  </FilesMatch>
</Directory>
or
Code:
<Directory "/home/example/public_html/fonts">
  <FilesMatch "\.(ttf|otf|eot|woff)$">
    <IfModule mod_headers.c>
      Header set Access-Control-Allow-Origin "*.example.com"
    </IfModule>
  </FilesMatch>
</Directory>
The second version is more restrictive.



* And if you need to load third-party assets, it's still a good idea to use protocol-relative URLs.
 
Status
Not open for further replies.