Create a custom Jekyll 404 page

Published: by Creative Commons Licence (Last updated: )

This article demonstrates how to create a custom Jekyll 404 page for Jekyll sites hosted on GitHub Page.

Things might be different if sites are hosted by other providers. Also it's worth noting that custom 404 pages will only be functioning on custom domain sites. For more detailed GitHub Pages official documentation, please see Custom 404 Pages - GitHub Help.

Create 404.html file

Create 404.html in the root directory of Jekyll site, which has to be an HTML file1.

Add YAML Front Matter

The goal here is to create a custom 404 page like all other pages using the same Jekyll theme, without creating a separately designed 404.html. Therefore, add YAML Front Matter section to the top of the 404.html and set the layout to be "page".

---
layout: page
title: 404
---

Add 404 content

Add the actual 404 content after the YAML Front Matter section.

---
layout: page
title: 404
---
<p>Sorry this page does not exist =(</p>

Redirect 404 page automatically

In order to redirect 404 page automatically, the easiest way might be using HTML meta tag, meta http-equiv="refresh".

  1. Add a <meta> tag in the <head> into Jekyll's default.html (e.g. mine resides in /_includes/themes/THEME_NAME/default.html)2.

  2. Set the meta tag's http-equiv attribute to "refresh", i.e <meta http-equiv="refresh">.

  3. Set meta tag's content attribute to something similar to content="5; url=/".
    • 5 is the number of seconds to wait before automatically redirecting. Setting to 0 means immediate redirecting.
    • url=/ sets the URL to be redirected to, which can also be set to any URLs like url=http://yizeng.me etc.
  4. Use Liquid's if-else statement to ensure the auto-redirecting happens to 404.html only.

Here is a completed example of default.html:

Test 404 page

  1. Build Jekyll server locally using jekyll serve, then go to URL localhost:4000/404.html, see if the custom 404 page works or not.

  2. Push to GitHub if everything looks fine.

  3. Go to the live site using the custom domain with a nonexistence URL, e.g. http://yizeng.me/go_404, see how the page looks and check if it can be redirected automatically or not.

  1. This statement no longer exists in official documentation, but I haven't had a chance to verify it. 

  2. "HTML <meta> http-equiv Attribute" example by W3schools.