Snippet: Host-Selective CORS Headers for Fonts using htaccess

Posted Friday, September 2, 2022 by Sri.Tagged MEMO
EDIT STATUS:working draft

This is the .htaccess code I'm using to allow access to two domains to serve font files. The way it works is by:

  1. Setting an environment variable called AccessControlAllowOrigin to the matching group from the Origin string. If there is no matching group, then the variable will be empty.
  2. The FilesMatch allows only font files, then sets the CORS headers only if the AccessControlAllowOrigin environment is not empty.
  3. Also, only allow GET requests specifically (not sure this is necessary, but other code like this allows PUT, DELETE, etc)
# allows font loads from or localhost:8080 for dev
<IfModule mod_headers.c>
SetEnvIf Origin "(http(s)?://|(http(s)?://localhost:8080)$" AccessControlAllowOrigin=$0
<FilesMatch ".(eot|otf|svg|ttf|woff|woff2?)$">
Header set Access-Control-Allow-Origin "*" env=AccessControlAllowOrigin
Header set Access-Control-Allow-Methods "GET" env=AccessControlAllowOrigin