How to redirect HTTP to HTTPS in MVC application (IIS7.5)

57,270

Solution 1

I use the following in Global.asax:

protected void Application_BeginRequest()
{
  if (FormsAuthentication.RequireSSL && !Request.IsSecureConnection)
  {
    Response.Redirect(Request.Url.AbsoluteUri.Replace("http://", "https://"));
  }
}

Solution 2

You can do it in code:

Global.asax.cs

protected void Application_BeginRequest(){
    if (!Context.Request.IsSecureConnection)
        Response.Redirect(Context.Request.Url.ToString().Replace("http:", "https:"));
}

Or You could add the same code to an action filter:

public class SSLFilter : ActionFilterAttribute {

    public override void OnActionExecuting(ActionExecutingContext filterContext){
        if (!filterContext.HttpContext.Request.IsSecureConnection){
            var url = filterContext.HttpContext.Request.Url.ToString().Replace("http:", "https:");
            filterContext.Result = new RedirectResult(url);
        }
    }
}

Solution 3

In the Global.asax.cs:

Simple redirect

protected void Application_BeginRequest()
{
    if (!Context.Request.IsSecureConnection
        && !Context.Request.IsLocal // to avoid switching to https when local testing
        )
    {
        // Only insert an "s" to the "http:", and avoid replacing wrongly http: in the url parameters
        Response.Redirect(Context.Request.Url.ToString().Insert(4, "s"));
    }
}

301 redirect: SEO best practice (Search Engine Optimization)

The 301 Moved Permanently redirect status response code is considered a best practice for upgrading users from HTTP to HTTPS (see Google recommendations).

So if Google or Bing robots will be redirected too, consider this:

protected void Application_BeginRequest()
{
    if (!Context.Request.IsSecureConnection
        && !Context.Request.IsLocal // to avoid switching to https when local testing
        )
    {
        Response.Clear();
        Response.Status = "301 Moved Permanently";
        Response.AddHeader("Location", Context.Request.Url.ToString().Insert(4, "s"));
        Response.End();
    }
}

Solution 4

I have the following ASP.NET MVC rewrite rule in Web.config file:

You can try this code with web.config file. If your URL is http://www.example.com then it will be redirect to this URL https://www.example.com.

<system.webServer>
    <rewrite>
        <rules>
             <rule name="http to https" stopProcessing="true">
              <match url="(.*)" />
              <conditions>
               <add input="{HTTPS}" pattern="^OFF$" />
              </conditions>
              <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

Solution 5

Use this code in web.config file for redirect http:// to https://

<configuration>
  <system.webServer>
    <rewrite>
        <rules>
            <rule name="HTTPS force" enabled="true" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{HTTPS}" pattern="^OFF$" />
                </conditions>
                <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
            </rule>
        </rules>
    </rewrite>
   </system.webServer></configuration>
Share:
57,270
Laxmi Lal Menaria
Author by

Laxmi Lal Menaria

Developer, Programmer &amp; Consultant with 12+ Years of Experience with ASP.NET, ASP.NET MVC, MySQL, MSSQL, JavaScript &amp; Amazon Web Services, US Medical Domain

Updated on July 08, 2022

Comments

  • Laxmi Lal Menaria
    Laxmi Lal Menaria almost 2 years

    I need to redirect my HTTP site to HTTPS, have added below rule but I am getting 403 Error when tried using http://www.example.com, it works fine when I type https://www.example.com in browser.

    <system.webServer>
        <rewrite>
            <rules>
                <rule name="HTTP to HTTPS redirect" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                    </conditions>
                    <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
    
  • farina
    farina about 13 years
    Moving my redirect logic to Application_BeginRequest() resolved an issue I was having where I was trying to do a redirect based on the typed URL.
  • Alex Marshall
    Alex Marshall over 11 years
    The Application_BeginRequest() worked perfectly for me, thanks.
  • cloudguy
    cloudguy about 8 years
    the code is not very correct: the following url http://example.com?someParam=http: will be transformed into https://example.com?someParam=https: modifying parameters string, consider using string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl; (taken from RequireHttpsAttribute which also do the exactly same thing)
  • OrElse
    OrElse about 8 years
    @cloudguy i suggest posting it as an answer
  • JustJohn
    JustJohn about 8 years
    Wow. I am very grateful to this thread. I googled "RequireHttpsAttribute" and ended up coding a solution that would disable redirects on my localhost dev environment but enable a custom class in production. Here is the thread I started: stackoverflow.com/questions/37042763/…
  • Matthieu Charbonnier
    Matthieu Charbonnier over 7 years
    If url's params contains an url or some other http: in it, it will be converted too. So I think you should just add the s in the 4th position: Response.Redirect(Context.Request.Url.ToString().Insert(4, "s"));. See my answer
  • juFo
    juFo over 7 years
    does not work if you have childactions (renderaction) ;-)
  • Nattrass
    Nattrass over 7 years
    Good spot, what does it do in that case?
  • juFo
    juFo over 7 years
    Just crash. "Child actions are not allowed to perform redirect actions. " "Exception Details: System.InvalidOperationException: Child actions are not allowed to perform redirect actions."
  • Sinjai
    Sinjai almost 7 years
    Should be selected answer IMO, not that I expect OP to come back after 5 years.
  • Arun Prasad E S
    Arun Prasad E S over 6 years
    @Matthieu Charbonnier Thanks a lot
  • Kirill Kostrov
    Kirill Kostrov over 6 years
    I agree with the post above - this one should be selected answer
  • stomy
    stomy about 6 years
    @Matthieu : Why not use !Context.Request.IsLocal?
  • Matthieu Charbonnier
    Matthieu Charbonnier almost 6 years
    @stomy Because I didn't know the IsLocal property. Thanks :)
  • Matthieu Charbonnier
    Matthieu Charbonnier over 5 years
    It's incomplete, because any http in the parameters of the url would be replaced too. See my answer
  • Ortund
    Ortund over 5 years
    @MatthieuCharbonnier where is the Application_BeginRequest() method called? Mine isn't doing anything...
  • Fred Wilson
    Fred Wilson about 5 years
    Be aware that 301 redirect will persist deep in the browser, so if you ever have to disable SSL for some reason, your users will have issues.
  • Calin Vlasin
    Calin Vlasin over 2 years
    Good job sir. The easiest way!
  • Adrian Hum
    Adrian Hum over 2 years
    My suggestion would be to use if (Context.Request.IsSecureConnection || Context.Request.IsLocal) return;