URL redirector with CloudFront Functions
This blog used to be hosted in Google Firebase, and before that, on Tumblr,
using the domain jslee.io
.
As of February 16, it’s now in Cloudflare Workers/Pages on a new domain
jslee.dev
.
I hadn’t got around to setting up a redirector yet. I’d assumed it would
require Lambda@Edge and CloudFront as I didn’t want to delegate the jslee.io
zone to Cloudflare’s DNS servers. However when I started looking at it this
evening, I was reminded that CloudFront Functions exists and is more or less
perfect for this application.
So, tonight I figured it all out. It was surprisingly easy. First, a short Javascript function:
async function handler(event) {
var response = {
statusCode: 302,
statusDescription: 'Found',
headers: {
"location": {
"value": "https://jslee.dev" + event.request.uri
}
}
};
return response;
}
and to attach it to a CloudFront distribution, some Terraform:
resource "aws_cloudfront_function" "jsleeio_redirector" {
name = "jsleeio-redirector"
runtime = "cloudfront-js-2.0"
comment = "redirector"
publish = true
code = file("${path.module}/redirector.js")
}
# adapted from Hashicorp's AWS provider docs; my real code uses a
# reusable "s3 + CloudFront static hosting" module that I made some
# time ago. This is very close, though:
resource "aws_cloudfront_distribution" "jsleeio_redirector_cdn" {
# ... other configuration ...
# function_association is also supported by default_cache_behavior
default_cache_behavior {
function_association {
event_type = "viewer-request"
function_arn = aws_cloudfront_function.jsleeio_redirector.arn
}
}
}
Finally, replace the old DNS records pointing at Firebase with new ones pointing at the CloudFront distribution:
resource "aws_route53_record" "jsleeio_redirector_aaaaa" {
for_each = toset(["A","AAAA"])
zone_id = data.aws_route53_zone.jsleeio.zone_id
name = "jslee.io."
type = each.key
alias {
name = module.jsleeio_redirector_cdn.cloudfront_domain_name
zone_id = module.jsleeio_redirector_cdn.cloudfront_hosted_zone_id
evaluate_target_health = true
}
}
Still have some cleanup to do, like purging all the Firebase and related gunk.
Also while I was in there I updated the theme and now it has lovely syntax highlighting in code blocks, and fixed the “read full post” links so they actually say “read full post” instead of an empty pair of square brackets.
Some tech debt smashed. This was definitely a good dopamine hit.