How to set a cache policy for Jekyll in Apache 2

Static sites are fast and they erase whole categories of potential issues I would have if this blog ran on a database bound dynamic CMS. This is not to say that things can’t be even better. Setting appropriate expiry headers makes a lot of sense on multiple levels: Clients won’t bug the server for files they already have (stylesheets, images, etc.), which lowers traffic costs and server load. This also meats that the site loads faster for the user and that we put less strain on the global internet infrastructure.

First we make sure that the mod_headers extension is activated for Apache 2:

sudo a2enmod headers

Then we edit the config file for the website and add a header for files that should not change very often.

<VirtualHost *:443>

...

  <FilesMatch ".(ico|pdf|flv|jpg|jpeg|png|gif|js|css)$">
    Header set Cache-Control "max-age=604800, public"
  </FilesMatch>
</VirtualHost>

What we are telling Apache here is that for any file that matches the provided Regex (files ending with .ico, .pdf, etc.) set a Cache-Control header for 604800 seconds (7 days).

If you know that your content won’t change often, or possibly never again, it absolutely makes sense to set an even longer time (i.e. years). In that case it would also make sense to include html/htm in the Regex.

Next we make sure that our configuration changes work as expected. This command will check the configuration and tell you about potential problems:

sudo apache2ctl -T

If that was successful we can restart Apache 2:

sudo service apache2 restart

Finally, of course, check with your browser that the site is actually up 😉.