Best way in to force https for an entire site?


About 6 months ago I rolled out a site where every request needed to be over https. The only way at the time I could find to ensure that every request to a page was over https was to check it in the page load event. If the request was not over http I would response.redirect("")

Is there a better way -- ideally some setting in the web.config?

12/29/2016 5:05:04 PM

Accepted Answer

Please use HSTS


<?xml version="1.0" encoding="UTF-8"?>
                <rule name="HTTP to HTTPS redirect" stopProcessing="true">
                    <match url="(.*)" />
                        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}"
                        redirectType="Permanent" />
                <rule name="Add Strict-Transport-Security when HTTPS" enabled="true">
                    <match serverVariable="RESPONSE_Strict_Transport_Security"
                        pattern=".*" />
                        <add input="{HTTPS}" pattern="on" ignoreCase="true" />
                    <action type="Rewrite" value="max-age=31536000" />

Original Answer (replaced with the above on 4 December 2015)


protected void Application_BeginRequest(Object sender, EventArgs e)
   if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false))
    Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"]
+   HttpContext.Current.Request.RawUrl);

that would go in the global.asax.cs (or global.asax.vb)

i dont know of a way to specify it in the web.config

6/1/2018 5:00:51 PM

The other thing you can do is use HSTS by returning the "Strict-Transport-Security" header to the browser. The browser has to support this (and at present, it's primarily Chrome and Firefox that do), but it means that once set, the browser won't make requests to the site over HTTP and will instead translate them to HTTPS requests before issuing them. Try this in combination with a redirect from HTTP:

protected void Application_BeginRequest(Object sender, EventArgs e)
  switch (Request.Url.Scheme)
    case "https":
      Response.AddHeader("Strict-Transport-Security", "max-age=300");
    case "http":
      var path = "https://" + Request.Url.Host + Request.Url.PathAndQuery;
      Response.Status = "301 Moved Permanently";
      Response.AddHeader("Location", path);

Browsers that aren't HSTS aware will just ignore the header but will still get caught by the switch statement and sent over to HTTPS.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow