Create a custom Jekyll 404 page
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
- Add YAML Front Matter
- Add 404 content
- Redirect 404 page automatically
- Test 404 page
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"
.
-
Add a
<meta>
tag in the<head>
into Jekyll'sdefault.html
(e.g. mine resides in /_includes/themes/THEME_NAME/default.html)2. -
Set the meta tag's
http-equiv
attribute to "refresh", i.e<meta http-equiv="refresh">
. - 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 to0
means immediate redirecting.url=/
sets the URL to be redirected to, which can also be set to any URLs likeurl=http://yizeng.me
etc.
- 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
-
Build Jekyll server locally using
jekyll serve
, then go to URLlocalhost:4000/404.html
, see if the custom 404 page works or not. -
Push to GitHub if everything looks fine.
-
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.
-
This statement no longer exists in official documentation, but I haven't had a chance to verify it. ↩
-
"HTML <meta> http-equiv Attribute" example by W3schools. ↩