Leveraging browser caching with Caddy

To get the maximum performance from your site, you need to make the user's browser cache your site. Google Pagespeed and tools like it complain a lot when that doesn't happen.

To activate browser caching, set appropriate headers. There are basically three methods to choose from:

  • Cache-Control
  • Expires
  • Etag

Expires is obsolete, so don't choose that. Etag and Cache-Control work differently: Etag tells the browser that a file has changed (and requires a server access), Cache-Control tells a browser how long to use its local copy of a resource before getting it from the server again.

Cache-Control and Etag can be used together, but I will focus on Cache-Control only in this post.

In the Caddyfile, inside the proxy declaration, you can add your own headers. A simple Cache-Control header looks like this:

https://mysite.com {
    tls anders@bornholm.se
    proxy / ghost-service:80 {
      transparent
    }

    header / {
      Cache-Control "max-age=86400"
    }
}

This will cache all requests to https://mysite.com for 24 hours.

If you have an admin UI, you probably don't want to cache that, or you will have a log of problems updating the site.

You can specify the same header directive multiple times for different paths (later directives override earlier directives).

For Ghost:

header / {
  Cache-Control "max-age=86400"
}

header /admin {
  Cache-Control no-cache
}

header /ghost {
  Cache-Control no-cache
}

For Wordpress:

header / {
  Cache-Control "max-age=86400"
}

header /wp-admin {
  Cache-Control no-cache
}
comments powered by Disqus