How to redirect HTTP to HTTPS in MVC application (IIS7.5)
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>
Laxmi Lal Menaria
Developer, Programmer & Consultant with 12+ Years of Experience with ASP.NET, ASP.NET MVC, MySQL, MSSQL, JavaScript & Amazon Web Services, US Medical Domain
Updated on July 08, 2022Comments
-
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 about 13 yearsMoving 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 over 11 yearsThe Application_BeginRequest() worked perfectly for me, thanks.
-
cloudguy about 8 yearsthe code is not very correct: the following url
http://example.com?someParam=http:
will be transformed intohttps://example.com?someParam=https:
modifying parameters string, consider usingstring url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
(taken from RequireHttpsAttribute which also do the exactly same thing) -
OrElse about 8 years@cloudguy i suggest posting it as an answer
-
JustJohn about 8 yearsWow. 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 over 7 yearsIf 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 over 7 yearsdoes not work if you have childactions (renderaction) ;-)
-
Nattrass over 7 yearsGood spot, what does it do in that case?
-
juFo over 7 yearsJust crash. "Child actions are not allowed to perform redirect actions. " "Exception Details: System.InvalidOperationException: Child actions are not allowed to perform redirect actions."
-
Sinjai almost 7 yearsShould be selected answer IMO, not that I expect OP to come back after 5 years.
-
Arun Prasad E S over 6 years@Matthieu Charbonnier Thanks a lot
-
Kirill Kostrov over 6 yearsI agree with the post above - this one should be selected answer
-
stomy about 6 years@Matthieu : Why not use !Context.Request.IsLocal?
-
Matthieu Charbonnier almost 6 years@stomy Because I didn't know the
IsLocal
property. Thanks :) -
Matthieu Charbonnier over 5 yearsIt's incomplete, because any
http
in the parameters of the url would be replaced too. See my answer -
Ortund over 5 years@MatthieuCharbonnier where is the
Application_BeginRequest()
method called? Mine isn't doing anything... -
Fred Wilson about 5 yearsBe 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 over 2 yearsGood job sir. The easiest way!
-
Adrian Hum over 2 yearsMy suggestion would be to use if (Context.Request.IsSecureConnection || Context.Request.IsLocal) return;