404to302 Lambda@Edge

Posted on Sun 22 September 2019 in misc

I discovered the 404to302 concept after a tweet by Aral Balkan, and immediately liked the idea. It solves a hard problem (keeping permalinks alive and working) in a fairly easy way: simply archive the old site, and avoid re-using the same permalink again. If you permalinks contain a date of some sort, this is very easy.

Since I've moved to host my static site on Amazon S3, I needed to add this functionality myself. Luckily, Amazon CloudFront allows you to run custom code when handling a request: Lambda@Edge. For this 404to302 concept, I hooked in to the "origin response" phase, inspecting every response for possible 404's. If the response is a 404, it looks up if a fallback URL is configured on the CloudFront distribution for this request, and returns a 302 to that location if present.

The code is available on GitHub.