ASP.NET HTTP to HTTPS redirect with www prefix
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);
}
精彩评论