2016-09-30 67 views
0

我试图重定向到https如何重定向到https并添加www。在链路

前面我用下面的代码在Global.asax中

protected void Application_BeginRequest() 
{ 
    if (!Context.Request.IsSecureConnection) 
     Response.Redirect(Context.Request.Url.ToString().Replace("http:", "https:")); 
} 

但我的问题是,我必须在链接的前面加上www, 即mywesite.se并重定向到https后,它像https://mywebsite.se但我希望它像https://www.mywebsite.se

+1

可以哟给我一个例子吗? –

+0

[组合URI和路径]的可能重复(http://stackoverflow.com/questions/679171/combining-uris-and-paths) – Andrea

回答

0

在这里你去(写入到web.config文件)

void Application_BeginRequest(object sender, EventArgs e) 
{ 
    string lowerCaseURL = HttpContext.Current.Request.Url.ToString().ToLower(); 
    if (lowerCaseURL.IndexOf("http://dotnetfunda.com") >= 0) // >= because http starts from the 0 position :) 
    { 
     lowerCaseURL = lowerCaseURL.Replace("http://dotnetfunda.com", "https://www.dotnetfunda.com"); 

     HttpContext.Current.Response.StatusCode = 301; 
     HttpContext.Current.Response.AddHeader("location", lowerCaseURL); 
     HttpContext.Current.Response.End(); 
    } 
} 

更换dotnetfunda.comyourwebsitedomainname.se

感谢

+0

impFunctions? –

+0

对不起,它只是替换功能。我将修改代码。 –

2

使用UriBuilder

var url = Context.Request.Url; 
var builder = new UriBuilder(url); 
builder.Scheme = "https"; 
if (!url.Host.StartsWith("www")) 
    builder.Host = "www." + url.Host; 

Response.Redirect(builder.Uri); 

声明:我没有测试这段代码。

2

可以在web.config添加重写规则

<rewrite> 
    <rules> 
     <clear /> 
     <rule name="Redirect non-www OR non-https to https://www"> 
      <match url=".*" /> 
      <conditions logicalGrouping="MatchAny"> 
       <add input="{HTTP_HOST}" pattern="^mywebsite.se$" /> 
       <add input="{HTTPS}" pattern="off" /> 
      </conditions> 
      <action type="Redirect" url="https://www.mywebsite.se/{R:0}" redirectType="Permanent"/> 
     </rule> 
    </rules> 
</rewrite> 
+0

是的,这似乎是更好的办法 – Andrey

+0

我得到了500内部错误 –

+0

你应该先删除你已经写在'Global.asax'! –

相关问题