Redirects with AWS ALB

This is a great new feature from AWS. No more need to spin up a separate server to do redirects.

Application Load Balancer now supports two new actions: redirect and fixed-response. You can configure these actions as part of the content-based routing rules, enabling you to offload this functionality to the load balancer. This simplifies deployments while benefiting from the scale, the availability, and the reliability of Elastic Load Balancing.

So here is our config for our ALB

resource "aws_alb" "eu_alb" {
  name            = "eu-alb"
  subnets         = ["${aws_subnet.public-1.id}", "${aws_subnet.public-2.id}", "${aws_subnet.public-3.id}"]
  security_groups = ["${aws_security_group.lb_sg.id}"]
  enable_http2    = "true"
  idle_timeout    = 600
}

And here is where the magic happens for a HTTP > HTTPS redirect

resource "aws_alb_listener" "front_end" {
  load_balancer_arn = "${aws_alb.eu_alb.id}"
  port              = "80"
  protocol          = "HTTP"

  default_action {
    order = 1
    type  = "redirect"
    redirect {
      host        = "#{host}"
      path        = "/#{path}"
      port        = "443"
      protocol    = "HTTPS"
      query       = "#{query}"
      status_code = "HTTP_301"
    }
  }
}