2023 update: the site has been re-written so this doesn’t currently work.
When I rebuilt this site, I did as everyone does and made sure I have a 404 page. It was sat as a static page quite happily until I started to misremember some URLs. I’d try to type out a link to share and think “should it have a hyphen or an underscore, does it have any capital letters or is it all lowercase?“. Of course I could easily navigate to the pages, but I wanted to save myself time. I was working on the sitemap when I saw a solution sat right in front of me…I could search against these URLs to find matches and suggest them to anyone who lands on my site.
I’m using farzher/fuzzysort to do this because it’s lightweight and does exactly what I’m after. By passing URL objects to the sort, I can search against pathname, host, or a whole URL. The fuzzysort library will handle typos or paths that plainly don’t exist, and when I know I have a single good match I can even redirect the user to it automatically. The result is that I’ve effectively built in pseudo-search functionality, or for the right terms this can even be used as a URL shortener!
Try these to see what happens:
- /thispagedoesnotexist - will return no suggestions
- /project - will give you some suggestions
- /projects/arraythsi - A mispelling with one result will redirect you.
- /fuzzysorting - this path doesn’t exist but a fuzzy match can be found. It treats the path as a search term.
In the future, I can see myself implementing something like this as a Cloudflare Worker that sits in front of a domain to handle the redirects on their edge network. This would improve the user experience and could still fall back on a plain old 404 page.
That’s all for now!