开发者

ASP.NET HTTP to HTTPS redirect with www prefix

开发者 https://www.devze.com 2023-01-17 22:21 出处:网络
I am using this simple code to redirect http to https on my billing landing page: if (!Request.IsSecureConnection)

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?


Like this:

if (!serverName.StartsWith("www."))
    serverName = "www." + serverName;


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号