Recently we decided to host a campaign website in AWS using EC2. The site had to run only under SSL / HTTPS, so we needed to redirect the users trying to use HTTP to the HTTPS protocol. That can be set up on IIS using the rewrite module, because this solution didn’t work. We ended up doing the redirect in code.

The way that the cluster is set up is: ELB listen to HTTPS (443), forwarding to HTTP (80) on the instance. ELB listen to HTTPS (80), forwarding to HTTP (80) on the instance. In this case we want to redirect the user to HTTPS.

The communication between the Load Balancer and the instance is clear HTTP. On each request we need to check if the user is using a secure connection, otherwise, we need to redirect him:


Notice, that if the request is from the ELB to the Health-check URL we don’t want to redirect, it would cause an infinite loop.

The way that the Elastic Load Balancer notify the instance the protocol that the user used to make the request is setting the HTTP Header: “X-Forwarded-Proto”.

SSL Helper, this would work locally and also on AWS:

Helper method to filter the health-check requests from ELB

Another thing to notice when you’re running a cluster behind ELB is that if you want to log the original request IP of the user, that is also set in a HTTP header, and this helper method would suffice to get it: