How to use CDN with Webfonts with Magento

From Brian Nelson Ramblings
Jump to: navigation, search

How to use CDN with Webfonts with Magento

Enabled a CDN on your Magento store and your Fonts and CORs-enabled images not working correctly.

When using Webfonts via @font-face or other CSS3 methods, some browsers like Firefox and IE will refuse to embed the font when it’s coming from a 3rd party URL because it’s a security risk. The solution is very simple, just add a few lines in your .htaccess file to permanently solve the problem.

Solution

Please add these lines to your .htaccess, preferably at the top:

Apache

# ----------------------------------------------------------------------
# CORS-enabled images (@crossorigin)
# ----------------------------------------------------------------------
# Send CORS headers if browsers request them; enabled by default for images.
# developer.mozilla.org/en/CORS_Enabled_Image
# blog.chromium.org/2011/07/using-cross-domain-images-in-webgl-and.html
# hacks.mozilla.org/2011/11/using-cors-to-load-webgl-textures-from-cross-domain-images/
# wiki.mozilla.org/Security/Reviews/crossoriginAttribute
<IfModule mod_setenvif.c>
 <IfModule mod_headers.c>
   # mod_headers, y u no match by Content-Type?!
   <FilesMatch "\.(gif|png|jpe?g|svg|svgz|ico|webp)$">
     SetEnvIf Origin ":" IS_CORS
     Header set Access-Control-Allow-Origin "*" env=IS_CORS
   </FilesMatch>
 </IfModule>
</IfModule>
# ----------------------------------------------------------------------
# Webfont access
# ----------------------------------------------------------------------
# Allow access from all domains for webfonts.
# Alternatively you could only whitelist your
# subdomains like "subdomain.example.com".
<IfModule mod_headers.c>
   <FilesMatch "\.(ttf|ttc|otf|eot|woff|woff2|font.css|css|js|html|json)">
   Header set Access-Control-Allow-Origin "*"
   Header set Access-Control-Allow-Headers "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
   Header set Access-Control-Allow-Methods "POST, GET, OPTIONS"
  </FilesMatch>
</IfModule>

Nginx

location ~ \.(ttf|ttc|otf|eot|woff|font.css|css)$ {
          add_header Access-Control-Allow-Origin "*";
}

After making those adjustments you will want to flush the CDN so that it picks up the new headers on the files with the Access-Control-Allow-Origin "*"

Testing the Headers

Once you have added the above code to your .htaccess / configuration file you can test to verify the cdn has picked up the new headers.

curl -I http://<CDNforyourdomain>/path/to/object/

You should see the follwoing in the headers:

Access-Control-Allow-Origin "*"

If you do not see that you will need to flush that object from the CDN so that it will pick up the new headers on the file.