How can I redirect HTTP(not secured) to HTTPS(Secured domain) URL in asp.net, here is my current code, which I am using in web.config
<configuration>
<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="Permanent" url="https://{HTTP_HOST}/{R:1}" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
After adding this code in web.config, I got an error "Not Secured"
Using web.config you can ask IIS to redirect to HTTPS using the code below
<system.webServer>
<rewrite>
<rules>
<clear />
<rule name="Redirect to https" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
<add input="{URL}" pattern="(.*)XYZ" negate="true" ignoreCase="true"/>
<add input="{HTTP_HOST}" matchType="Pattern" pattern="^localhost(:\d+)?$" negate="true" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
</rule>
<rule name="redirect qawithexperts.com to www.qawithexperts.com">
<match url=".*"/>
<conditions logicalGrouping="MatchAll">
<add input="{HTTP_HOST}" pattern="^www.*" negate="true"/>
<add input="{HTTP_HOST}" pattern="localhost" negate="true"/>
</conditions>
<action type="Redirect" url="http://www.qawithexperts.com/{R:0}"/>
</rule>
</rules>
</rewrite>
</system.webServer>
Now, remember on server, you should bind your application to :443 port (which is used for https)
Login to you server-> Open IIS-> Expand server(Win---) -> Expand Sites -> Select Your Website -> In the right hand side pane (Actions Tabs) -> Click on Bindings -> Select "Add" -> Edit Site Bindings Details -> Click "ok"
<add input=”{HTTPS}” pattern=”off” ignoreCase=”true” /> is the main redirection rule that redirects HTTP requests to HTTPS (this is called 301 redirection)
Try this code in your Global.asax (without using Web.config approach)
protected void Application_BeginRequest(Object sender, EventArgs e)
{
switch (Request.Url.Scheme)
{
case "https":
Response.AddHeader("Strict-Transport-Security", "max-age=300");
break;
case "http":
var path = "https://" + Request.Url.Host + Request.Url.PathAndQuery;
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", path);
break;
}
}
The above code is using HSTS by returning the "Strict-Transport-Security" header to the browser
Or try this code
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);
}
}
One of them will work if you are on ASP.NET web forms website
For those who are using ASP.NET MVC & came across this question, you can use these 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);
}
}
}
I have found one more better way to redirect user from http to https in ASP.NET MVC
You can create a CustomRequireHttpsFilter class for handling Request
public class CustomRequireHttpsFilter : RequireHttpsAttribute
{
protected override void HandleNonHttpsRequest(AuthorizationContext filterContext)
{
// The base only redirects GET, but we added HEAD as well. This avoids exceptions for bots crawling using HEAD.
// The other requests will throw an exception to ensure the correct verbs are used.
// We fall back to the base method as the mvc exceptions are marked as internal.
if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)
&& !String.Equals(filterContext.HttpContext.Request.HttpMethod, "HEAD", StringComparison.OrdinalIgnoreCase))
{
base.HandleNonHttpsRequest(filterContext);
}
// Redirect to HTTPS version of page
// We updated this to redirect using 301 (permanent) instead of 302 (temporary).
string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
if (string.Equals(filterContext.HttpContext.Request.Url.Host, "localhost", StringComparison.OrdinalIgnoreCase))
{
// For localhost requests, default to IISExpress https default port (44300)
url = "https://" + filterContext.HttpContext.Request.Url.Host + ":44300" + filterContext.HttpContext.Request.RawUrl;
}
filterContext.Result = new RedirectResult(url, true);
}
}
and then use it as below in FilterConifg.cs
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//add filter
filters.Add(new CustomRequireHttpsFilter());
}
}
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly