How to protecting the webfonts files
The goal is to prevent hotlinking, stopping other websites from using your font files without permission, while ensuring they work perfectly for your own visitors.
1.
Protection with .htaccess on Apache
After uploaded the webfont files onto to your site www.yourdomain.com into a subdirectory called /fonts/ find or make a new file named .htaccess inside this directory and paste these lines into it:
# ENABLE THE REWRITE ENGINE
RewriteEngine On
# BLOCK HOTLINKING FOR FONT FILES
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?yourdomain\.(com|local) [NC]
RewriteRule \.(woff2?|ttf|eot|svg)$ - [NC,F,L]
# DISABLE DIRECTORY LISTING (OPTIONAL BUT RECOMMENDED)
Options -Indexes
Replace yourdomain.com by your own host name.
The dot before com must be escaped with a backslash.
The part (www.) means the rule accepts the domain with or without the www prefix.
The part (s)? means the rule works with HTTP and HTTPS.
These rules block all font requests that do not come from your domain. The server sends a 403 error in those cases.
Options -Indexes prevents directory listing inside the fonts folder.
If you get a 500 error, your hosting does not allow .htaccess overrides. Move the same rules into the main Apache configuration.
If you use IIS, convert these rules into IIS rewrite rules using the available import tools.
Some browsers and extensions do not send referrer information. When this happens the font may fail to load and the browser will use fallback fonts.
2.
Use CORS Headers (More Modern)
For a more browser-enforced approach, you can use Cross-Origin Resource Sharing (CORS) headers to specify which domains are allowed to request your fonts.
Add this to your .htaccess file (can be combined with the hotlinking rules):
# ALLOW FONT ACCESS ONLY FROM YOUR DOMAIN
<filesmatch "\.(woff2?|ttf|eot|svg)$"="">
Header set Access-Control-Allow-Origin "https://www.yourdomain.com"
# Use the line below if you don't use 'www'
# Header set Access-Control-Allow-Origin "https://yourdomain.com"
How it works: Modern browsers check this header when a page from a different domain tries to load your font. If the requesting page’s domain isn’t on the allowed list, the browser itself blocks the request.
3.
Solution via CDN (Cloudflare, etc.)
If you use a CDN like Cloudflare, enable their built-in Hotlink Protection feature:
-
Log in to your Cloudflare dashboard.
-
Go to Scrape Shield (or Security > Scrape Shield depending on your dashboard version).
-
Turn “Hotlink Protection” ON.
-
Cloudflare will automatically intercept and block requests for your images (and often other assets) that do not come from your own domain.
Note: The suggestion to “put font files in a directory named hotlink-ok” is not a valid Cloudflare feature and should be ignored.
This post is also available in 中文.