Elastic Beanstalk with 'native' HTTPS redirection on ALB

If you search the internet on how to redirect http to https for Elastic Beanstalk you often find information on how to configure the accompanied webserver provided by the Elastic Beanstalk platform

using ebextensions. Until recently this was the only way to accomplish this. For some time now we can perform this action on the Application Loadbalancer itself.

Let’s walk through the neccesary configuration steps.

Create ebextensions

Create a file (ex: alb.config.) in your .ebextensions folder with the following content. (Create an .ebextensions folder if you don’t have one)

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

Remove default Listener

Elastic Beanstalk creates a default Listener on the Application Loadbalancer which needs to be removed to make this work. And because we deploy all our resources with Cloudformation we can easily do this by adding the following to our OptionSettings

- Namespace: aws:elbv2:listener:default
  OptionName: ListenerEnabled
  Value: false

Enable TLS listener

Since we want to redirect http to https we do need a TLS listener configured on our Application Loadbalancer. This is also configured using Cloudformation by adding following to OptionSettings

- Namespace:  aws:elbv2:listener:443
  OptionName: ListenerEnabled
  Value: true
- Namespace:  aws:elbv2:listener:443
  OptionName: Protocol
  Value: HTTPS
- Namespace:  aws:elbv2:listener:443
  OptionName: SSLCertificateArns
  Value: !Ref CertificateArnParam
- Namespace: aws:elbv2:listener:443
  OptionName: SSLPolicy
  Value: ELBSecurityPolicy-TLS-1-1-2017-01

That’s it. After updating your cloudformation stack you should have http to https redirection without having to modify the webserver used by the Elastic Beanstalk platform.