4

I'm currently preloading font files for one webpage on WordPress.

So https://example.com not preloaded. https://example.com/test/ preloaded font file.

This is what I've got in .htaccess.

<Files "/test/">
Header add Link "</fonts/poppins.woff2>; rel=preload; as=font; type=font/woff2; crossorigin"
</Files>`

The link works fine, it's the conditional loading that I'm struggling with. Tried adding wildcards, plus the full URL, etc, but no joy.

Am I right in thinking it's not the syntax, but it needs allowing before it works?

MrWhite
  • 12,647
  • 4
  • 29
  • 41

1 Answers1

6

It is the syntax...

The <Files> directive matches against filenames only (eg. foo.php) - when the request maps to physical files on the filesystem. Since this is WordPress, I assume /test/ is not even a filesystem directory - it's simply a URL-path?

You can use mod_setenvif to set an environment variable when this URL-path is requested and then set the Header conditionally based on this environment variable.

This should go before the WordPress front-controller, near the top of your .htaccess file.

For example:

SetEnvIf Request_URI "^/test/" PRELOAD_FONT
Header add Link "</fonts/poppins.woff2>; rel=preload; as=font; type=font/woff2; crossorigin" env=PRELOAD_FONT

The regex ^/test/ matches any URL-path that starts /test/. If this should only match the single URL /test/ then append an end-of-string anchor to the regex: ^/test/$.

Note the extra env=PRELOAD_FONT argument at the end of the Header directive. The header is only set when the PRELOAD_FONT environment variable, set by the preceding SetEnvIf directive, is also set.

MrWhite
  • 12,647
  • 4
  • 29
  • 41
  • 1
    Thanks for this. I will try it out. Much appreciated for the explanation. Can't upvote yet, so not being ignorant. :) – David Elstob Mar 18 '20 at 22:47
  • Just like to add - it works great. I'll update my Server Push / Preload blog post with the information, so cheers. – David Elstob Mar 18 '20 at 22:56