How to redirect HTTP traffic to HTTPS when using AWS ALB
This is a troubleshooting history about composing ALB-EC2 infrastructure. I got the solution from this following document.
Problem
For secure network service, we set redirect setting on our web server. I’m using Apache normally, so at that time, I write config file as shown below.
<VirtualHost *:80>
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
# ...
</VirtualHost><VirtualHost *:443>
# ...
</VirtualHost>
It works if you just only use EC2 instance. But if you want to use application load balancer(ALB), this setting will be becoming cause of the ERR_TOO_MANY_REDIRECTS
error.
Solution
To identify what protocol is used by load balancer, we should check X-Forwarded-Proto header.
If you don’t know what is XFP header, check this definition defined by Mozilla.
The X-Forwarded-Proto (XFP) header is a de-facto standard header for identifying the protocol (HTTP or HTTPS) that a client used to connect to your proxy or load balancer. Your server access logs contain the protocol used between the server and the load balancer, but not the protocol used between the client and the load balancer. To determine the protocol used between the client and the load balancer, the X-Forwarded-Proto request header can be used.
Anyway, I modified my Apache config file as shown below.
<VirtualHost *:80>
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]
# ...
</VirtualHost>
- I modifed
RewriteCond
- I removed definition about 443 port
We check only XFP header to identify protocol. And we have not to define 443 port of virtual host setting, because ALB offer HTTPS communication automatically if we set simple listener and ACM.
Conclusions
I always stuck when I composed infrastructure, so I decided to record troubleshooting history for myself. I hope this history help someone who has same trouble to me.