views:

33

answers:

2

I am using this simple code to redirect http to https on my billing landing page:

if (!Request.IsSecureConnection)
{
    // send user to SSL 
    string serverName =HttpUtility.UrlEncode(Request.ServerVariables["SERVER_NAME"]);        
    string filePath = Request.FilePath;
    Response.Redirect("https://" + serverName + filePath);
}

I need it to also check for and add www to the url if it is not already in the url. What do I need to add to this code to accomplish this?

A: 

The following code assumes that if the server name doesn't start with a "www." then the remedy is to prepend whatever the current servername is with "www."

if (!Request.IsSecureConnection)
{
    // send user to SSL 
    string serverName = Request.ServerVariables["SERVER_NAME"];
    if (!serverName.ToLowerCaseInvariant().StartsWith("www.")) {
       serverName = string.Format("www.{0}", serverName);
    }
    string filePath = Request.FilePath;
    Response.Redirect("https://" + serverName + filePath);
}

Personally, I don't like this method of doing things. I usually create a setting named something like SecureDomain and then use logic to verify whether the current ServerName matches that. Something like this.

// Suppose the value of GlobalAppSettings.SecureDomain
// is something like www.securestore.com

if (!Request.IsSecureConnection)
{
    // send user to SSL 
    string serverName = Request.ServerVariables["SERVER_NAME"];
    if (string.Compare(serverName, GlobalAppSettings.SecureDomain, true) != 0) {
       serverName = GlobalAppSettings.SecureDomain;
    }
    string filePath = Request.FilePath;
    Response.Redirect("https://" + serverName + filePath);
}
jessegavin
Hey Jesse, Thanks very much for your assistance. I'm confident that your method would work well, also, but the other response was very simple to just insert inside of what I already had. - Jesse(2)
Prismatics
A: 

Like this:

if (!serverName.StartsWith("www."))
    serverName = "www." + serverName;
SLaks
Your example doesn't take case into account. What if the servername was WWW.domain.com, then the result would be www.WWW.domain.com.
jessegavin
Whoa! That was simple! That worked great, thanks very much.
Prismatics
@jessegavin at first glance, I thought that would be the case, but it doesn't duplicate the www.
Prismatics
@Prismatics You're wrong.
jessegavin
@jessegavin: Domain names are normalized to lowercase. However, you're right; I should have passed `, StringComparison.OrdinalIgnoreCase)`.
SLaks
Phooey. You're right. Thanks @SLaks. Sorry for accusing you of being wrong @Prismatics.
jessegavin