If you're serving web fonts from a different origin than your website, you might find that they don't load in certain browsers. Here's why that happens and how you can fix it.
You're probably familiar with the same-origin policy that browsers follow. This policy prevents malicious scripts on one page from accessing sensitive data on other pages. What you probably don't know is that this rule applies to web fonts...sometimes.
You see, WebKit-based browsers incorrectly allow cross-domain fonts to load, but other browsers (correctly) do not. This is why your fonts might load in Chrome and Safari, but not in Firefox.
How To Use Cross-domain Fonts
The most common use of cross-domain fonts is loading them from a CDN, which is usually faster than hosting them yourself and saves you bandwidth. There may be other reasons, too.
For example, in Surreal CMS, we load a copy of your webpage on our domain to let you edit it. Of course, scripts, stylesheets, and web fonts are still loaded from your domain, which means your web fonts might not show up in our editor.
Fortunately, you can fix this problem by enabling CORS for web fonts.
CORS Config for Apache
To enable CORS in Apache, add the following to your .htaccess
file.
<FilesMatch ".(eot|otf|ttf|woff)">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
This tells Apache to set the Access-Control-Allow-Origin
header for all files ending with a
web font extension. (If you're managing your own server, you can add this to your main Apache
config instead so it applies to all sites automatically.)
CORS Config for nginx
To enable CORS in nginx, add the following to your server's config. (Don't forget to reload nginx afterwards!)
if ($filename ~* ^.*?\.(eot)|(otf)|(ttf)|(woff)$){
add_header Access-Control-Allow-Origin *;
}
Similarly, this tells nginx to set the Access-Control-Allow-Origin
header for web font
files.
Checking Your CORS Config
Once you've updated your server, you can check for the Access-Control-Allow-Origin
header using this command. Just point <font-url>
to any of the font files on your
server.
curl -s -I <font-url> | grep -i "access-control-allow-origin"
If you've configured CORS correctly, you should see the following output.
Access-Control-Allow-Origin: *
If you don't see this, here are some things you can try:
- Make sure the URL you entered is correct
- Double check your server's config
- Make sure you've reloaded your server (not necessary for
.htaccess
configs) - Make sure your server isn't caching requests
- If you're using a CDN, make sure you've invalidated cache for web font files
Now that you've enabled CORS for web fonts, you'll see them load correctly in all browsers!