httpsaws-cloudformationhttp-redirectelastic-load-balanceramazon-elb

AWS CloudFormation Application Load Balancer - how to redirect HTTP listener to HTTPS listener?


I am trying to write a CloudFormation template for ALB, but got stuck on the point where I would like to redirect ALB's HTTP listener's traffic to HTTPS listener. Docs mention only forwarding/redirection to the target group.

I am aware that it is achievable using the web interface (AWS Console), which I want to avoid. Also handling it on the server is a no go for me.

Is this ALB's feature simply not implemented in CloudFormation, but exists in Console?


Solution

  • On November 19, 2018 Amazon introduced the RedirectConfig for the Elastic Load Balancer Listener. This listener type is also used for the Application Load Balancer (ALB).

    Below you find an example configuration for the usual HTTP to HTTPS redirect. Replace 'PublicLoadBalancerBackend' with your load balancers CloudFormation object.

      PublicLoadBalancerHttpRedirectListener:
        Type: AWS::ElasticLoadBalancingV2::Listener
        DependsOn:
          - PublicLoadBalancerBackend
        Properties:
          DefaultActions:
            - RedirectConfig:
                Host: "#{host}"
                Path: "/#{path}"
                Port: 443
                Protocol: "HTTPS"
                Query: "#{query}"
                StatusCode: HTTP_301
              Type: redirect
          LoadBalancerArn: !Ref 'PublicLoadBalancerBackend'
          Port: 80
          Protocol: HTTP
    

    CloudFormation Documentation on the RedirectConfig: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-listener-redirectconfig.html

    CloudFormation Documentation on the Listener Action: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-listener-defaultactions.html