SSL redirection

From www.mydomain.com or mydomain.com TO https://www.mydomain.com

To accomplished the above redirection, there are few options, you can do it in IIS, web.config, live server sitting, redirection in the code level

Web.config

In web.config you can put the below code inside tag and that should work:

<rewrite>
<rules>
<rule name=”Redirect domain.com to www” patternSyntax=”Wildcard” stopProcessing=”true”>
<match url=”*” />
<conditions>
<add input=”{HTTP_HOST}” pattern=”domain.com” />
< /conditions>
<action type=”Redirect” url=”https://www.domain.com/{R:0}” />
< /rule>
< /rules>
< /rewrite>

but if you are using pre IIS 6, you need to use urlrewritingnet tag in web.config

<urlrewritingnet>
<rewrites>
<add name=”secure” virtualUrl=”http\://(.*)” destinationUrl=”https://$1″ ignoreCase=”true” redirect=”Domain” />
</rewrites>
</urlrewritingnet>

Global.asax
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);
   }
}

But if you want to do a permanent 301 redirection, then you can use the below code

Current.Response.Status = "301 Moved Permanently"
      Current.Response.AddHeader("Location", "https://"+ Current.Request.RawUrl)
      Current.Response.End()

the difference between 301 redirection and a normal Response.redirection (302) is that 301 is permanent redirection which is important for the search engine to know it has been moved to a new page.

IIS Setting
  1. open IIS manager
  2. Click ‘URL Rewrite’
  3. Click on ‘Add rule’ in action panel
  4. user wild card
    Condition input: {HTTP_HOST}
    Check if input string: Matches the Pattern
    Pattern: domain.com
    Ignore case: checked
    and action set to redirect to the new site. This is a replacement for web.config

From Https://www.mydomain.com to Https://mydomain.com

In a DNS entry. You could add a CNAME entry that looks like this:
www.mydomain.com. CNAME mydomain.com.

From Https://mydomain.com to Https://www.mydomain.com

If the above case hits an invalid SSL certificate, this is because you the the SSL domain doesn’t match and I believe all the methods above won’t do a proper redirection unless the client accepts the SSL error. This is because SSL handshake happens before the connection is establish so any redirection will not apply.

The solution in this case is to get the right SSL, a wild card SSL or a Subject Alternate Name (SAN) SSL certificate.

this is also why https://amazon.com is different than https://www.amazon.com

By Michael Siu

Tagged with: ,
Posted in .NET, C# Programming, Technical

Leave a Reply