Friday, February 20, 2015

Forcing HTTPS on ASP.NET Application behing SSL offloading Elastic Load Balancer (ELB)

One of the first problems encountered when trying to move ASP.NET MVC2 Application from regular dedicated hosting to cluster of Amazon's EC2 instances with Elastic load balancer (ELB) distributing traffic between them was endless loop of 303 redirects. Seems like ASP.NET application being moved to new infrastructure had following section in rewrite rules of web.config file forcing every non-HTTPS requests to be redirected to HTTPS-one:

1
2
3
4
5
6
7
8
9
<rules>
        <rule name="Redirect to HTTPS" stopProcessing="true">
          <match url="(.*)" />
          <conditions>
            <add input="{HTTPS}" pattern="^OFF$" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther" />
        </rule>
 </rules>

Problem here is that Elastic Load Balancer is configured to offload HTTPS traffic, and forward plain HTTP request to EC2 instance, so instance's CPU is less utilized. Problem here is that rewrite condition is that incoming request is HTTPS (which is NOT), and thus endless 303 redirects occur. Fortunately, according to non-written standard, Amazons ELB  forwards 'HTTP_X_FORWARDED_PROTO' header with origin request protocol as value, thus above condition could be replaced with
'do not apply this rule if content of HTTP_X_FORWARDED_PROTO header is 'https' or in web.config:


1
2
3
4
5
6
7
8
9
<rules>
        <rule name="Redirect to HTTPS" stopProcessing="true">
        <match url="(.*)" />           
  <conditions>
      <add input="{HTTP_X_FORWARDED_PROTO}" pattern="https" negate="true" />
  </conditions>   
        <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther" />
        </rule>
 </rules>

No comments:

Post a Comment