In the old days, developers and webmasters were forced to use local fonts from their computeres to visualize web fonts in their web pages. But today you can load a big number of fonts from remote sources to get a more rich font experience and enchance your visitor usability while browsing your website.
On this article you will learn how to enable CORS on LiteSpeed and Apache WebServer so you can load your fonts normally without any issue.
One of the most typical issues while loading fonts from remote servers (specially CDN providers) is that sometimes it simply doesn’t work, your font is not loading ok from the CDN provider, and your site looks like sh*t.
Why is my font not loading while using a CDN?
To answer that question, first you need to know about CORS.
Web browsers like Firefox, Internet Explorer, Opera and Chrome will not allow you to embed web fonts if they detect that it’s hosted on an external website. The CORS mechanism will prevent you from loading those fonts, but you can setup a whitelist to allow those resources to be loaded from an external website, or from everywhere.
Enable CORS on LiteSpeed Web Server
Let’s enable CORS on LiteSpeed and Apache Web Servers.
In order to load fonts and other resources from your CDN, you must place this code inside an .htaccess:
# Images and General graphics <FilesMatch "\.(gif|png|jpe?g|svg|svgz|ico|webp)$"> SetEnvIf Origin ":" IS_CORS Header set Access-Control-Allow-Origin "*" env=IS_CORS # Webfons <FilesMatch "\.(ttf|ttc|otf|eot|woff|font.css|css|woff2)$"> Header set Access-Control-Allow-Origin "*"
Now, test this out using ‘curl -I’ command against your domain:
curl -I www.yoursite.com
[webtech@localhost ~]$ curl -I www.nixcp.com HTTP/1.1 404 Not Found Date: Tue, 17 Jan 2017 13:09:11 GMT Connection: keep-alive Set-Cookie: __cfduid=d7204a727c28f6f2fcde94ddb7b66746b1484658551; expires=Wed, 17-Jan-18 13:09:11 GMT; path=/; domain=.mp3teca.com; HttpOnly Accept-Ranges: bytes Access-Control-Allow-Origin: * X-Turbo-Charged-By: LiteSpeed CF-RAY: 322a0a49b7b76821-EZE [webtech@localhost ~]$
If you see “Access-Control-Allow-Origin: *”, then that means your web fonts should load fine from now on. If they don’t, try cleaning your browser cache and restaring your HTTP server, and if that still doesn’t work, contact your CDN provider for support.
While I used this for LiteSpeed, it works perfectly for Apache too as it’s a simple .htaccess configuration.