Home
Support Forums

How to preconnect/dns-prefetch/preload via Netlify _headers file

I’m trying to move my resource hints (preconnect, dns-prefetch, and preload) from the head tag in my HTML to my site’s (Netlify-specific) _headers file.

My site is a SPA.

For example, I’m trying to change this:

<!-- FILE: _index.html -->

<head>
    <link rel="preconnect" href="https://api.mysite.com" />
    <link rel="dns-prefetch" href="https://img.mysite.com" />
    <link rel="preload" href="/styles/globals.css" as="style" />
</head>

to this:

# FILE: _headers

/index.html
  Link: <https://api.mysite.com>; rel="preconnect",
  Link: <https://img.mysite.com>; rel="dns-prefetch",
  Link: </styles/globals.css>; rel="preload"; as="style"

Here’s the thing I can’t figure out:

The above works if putting it in a cache all route (i.e. /* instead of /index.html). However, that causes the link header to be sent for all requests, which of course is not desirable. I’ve also tried /*.html, but that also does not work. How can I send the link header for only index.html?

This is expected behaviour of the current implementation.

_headers won’t work for /*.html, though it would work for other file extensions. This is because html files can be served with or without the extension, thus it’s only possible to use /* route for them.