Cross domain font woes in Firefox
March 21, 2012 § 5 Comments
We love using custom fonts with CSS @font-face declarations and have done so on a number of our recent projects. One thing has caught us out on a couple of occasions though. Here’s the scenario:
You’re building a site, everything is going well with the styling. Your custom font is looking good on your local version of the site, it’s been checked in staging and looks good there. You launch the site, it looks good everywhere… except Firefox. Your favourite development browser (well, mine at least, apparently some people like Chrome a lot these days) is no longer showing that lovely font. You can’t reproduce this on your own machine, everything seems lost.
CDNs and subdomains
When this has happened to us, it has always come down to one thing: for highly trafficked sites we use a CDN to serve static assets like CSS, JavaScript and fonts. These files not only come from a different server, they get served from different subdomains (normally “media#{n}.awesomenewsite.com” where n is between 0 and 3). The problem: Firefox allows you to request fonts from the same domain but requires access control headers to be set when requesting them across different domains.
Access Control
So, how do you set these headers? We use nginx as a web server so we use a block a bit like the following:
location ~* ^/assets/fonts/ {
gzip_static on;
expires max;
add_header Cache-Control public;
add_header Access-Control-Allow-Origin http://awesomenewsite.com;
}
If you use Apache, you could add an htaccess file in the folder where the font files live with the following in:
Header set Access-Control-Allow-Origin "*"
(That snippet thanks to this StackOverflow answer.)
Rather than setting the requesting domain, you can also set the origin to * to allow any domain to request the resource. It is probably best practice to define the URLs yourself, but as it is only Firefox that respects this header in reality it doesn’t matter too much.
Fonts for everyone
It’s easy to add the access control headers for these fonts, but also very easy to forget! I hope this can serve as a reminder to all of us, so we can all get fonts right on the web.
[…] few months back we looked at issues related to showing custom fonts in firefox (see Cross domain font woes in Firefox). Since then we have also started hosting more and more sites on heroku where you have no control […]
I’m having the same problem but the font looks clear and good in Firefox and in Chrome it looks all pixelated I think this is due to Chrome not using the default cleartype and firefox using the default.
There’s a typo – here’s the one without
Header set Access-Control-Allow-Origin “*”
Not quite sure what you mean there, Jin?
Thank ypu!