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!
Thanks for reading! š