AWS: How to redirect HTTP to HTTPS on App Load Balancer?
It's now possible to directly do some redirection in any ALB rule, see related AWS announcement.
To unconditionally redirect all queries from HTTP to HTTPS, you have to configure the HTTP listener with only the default rule/action to permanently redirect (301) all request with the same host, path and query on the HTTPS port (typically: 443) with the HTTPS protocol:
Assuming that you are running Microsoft Windows in an EC2 instance, and you are using IIS to configure two web sites, siteA and siteB. Set up siteA to bind at port 81 and siteB to bind at port 82.
STEP 1:
In AWS console, select "Target Groups" under "Load Balancing". Create two target groups:
1. siteA-target-group with your web server instance ID and port 81
2. siteB-target-group with your web server instance ID and port 82
Note: you can add more web server instances in the target group for load balancing and failover purposes.
STEP 2:
In AWS ALB, there are two listeners, one for port 80 and one for port 443.
For HTTP (80), add 2 rules:
1. if host is siteA.com, redirect to https://#{host}:443/#{path}?#{query}
2. if host is siteB.com, redirect to https://#{host}:443/#{path}?#{query}
For HTTPS (443), add 2 rules:
1. if host is siteA.com, forward to siteA-target-group
2. if host is siteB.com, forward to siteB-target-group
STEP 3:
On your DNS provider, set up a CNAME for siteA.com to point at the ALB's DNS name. Similarly, set up a CNAME for siteB.com.
When the above setup is completed, test connecting to http://siteA.com or http://siteB.com
i) traffic hits the ALB port 80
ii) host header matches the rule "siteA.com" and redirect traffic to port 443
iii) traffic hits the ALB port 443
iv) host header matches the rule "siteA.com" and forward to target group siteA-target-group
v) siteA-target-group points at port 81 on the web server and the page is served.