Custom 404 handler on Cloudflare Pages
Moving from WordPress to JAMstack has been an interesting journey, although not nearly as challenging as I expected. One of the migration tasks that did give me a little trouble, however, was setting up a custom 404 error page.
I use Hexo as my CMS for this website, and some advice I found online said to just create a 404.md
or 404.html
in your /source
directory. However, using hexo serve
to test locally doesn’t seem to make use of that file, and instead I just got a “cannot get /foo” type of message. What I discovered was that 404 handling is highly dependent on your web host, which makes sense especially for a static site. Cloudflare Pages is pretty new at the time of this writing, so the documentation doesn’t cover everything yet, but the third bullet point on the list of known issues cleared things up for me.
Basically, if there is a 404.html
file in your Cloudflare Pages project, it will serve that when a file is not found. Otherwise, it will serve /index.html
, so if you don’t have a 404 page, any invalid URLs will take you straight to your homepage.
I initially tried creating my 404 page with hexo new page 404
, but that creates a /source/404
directory and the file itself at /source/404/index.md
. While that might work, I prefer to have a page called 404.md
directly in my /source
directory just to be safe. That gets used to generate a 404.html
and then you’re good to go!