2

I'm using the following to force https on my site:

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);
    }
}

Is there anything I can add to this code that will also strip "www" from the url as well? That way if a user types "http://www.URL.net" it will automatically go to "https://URL.net".

**note: I'm using IIS6 and can't upgrade to IIS7.

enjoimark
  • 61
  • 9
  • 2
    Have you considered maybe trying to do this using your webserver? – logixologist Nov 18 '13 at 23:29
  • why not doing this by modifying the web.config? – trajce Nov 18 '13 at 23:30
  • Other than replacing ``Request.ServerVariables["HTTP_HOST"]`` with ``Regex.Replace(Request.ServerVariables["HTTP_HOST"], @"^www\.", "", RegexOptions.IgnoreCase)``? – acfrancis Nov 18 '13 at 23:35
  • take a peak at http://stackoverflow.com/questions/46347/iis7-http-https-cleanly and follow that to http://jameskovacs.com/2007/05/09/how-to-autoredirect-to-a-sslsecured-site-in-iis/ you'll need to tweak the approach. – Mike Miller Nov 18 '13 at 23:45
  • I'm using IIS6. acfrancis - I tried that, didn't do anything. Still lets me use "www" in the url – enjoimark Nov 18 '13 at 23:57
  • acfrancis - nevermind I think I had a typo. Your suggestion did work. – enjoimark Nov 19 '13 at 19:22

2 Answers2

1

User "acfrancis" solved the problem:

replace Request.ServerVariables["HTTP_HOST"] with Regex.Replace(Request.ServerVariables["HTTP_HOST"], @"^www\.", "", RegexOptions.IgnoreCase)

So the full 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://" + Regex.Replace(Request.ServerVariables["HTTP_HOST"], @"^www\.", "", RegexOptions.IgnoreCase) + HttpContext.Current.Request.RawUrl);
    }
}

Works perfectly. Forces HTTPS and removes WWW from the url.

enjoimark
  • 61
  • 9
0

I recommend doing this with IIS' URL Rewriter extension.

In addition to rewriting URLs, it can also perform redirections, including a built-in template for canonical hostnames. That way the redirection is applied to every request, not just those that go through ASP.NET.

Dai
  • 141,631
  • 28
  • 261
  • 374