ASP.NET处理301重定向方法
关于百度等搜索引擎对于是否带"www"前缀的域名的识别问题:即搜索引擎会将www.abc.com和abc.com识别为不同的两个域名,这样做的后果就是分散了对网站的关注度,不利于网站的宣传和推广。
仅仅是通过Response.Redirect方法来重定向该连接,虽然可以将连接进行重定向,但是无法解决搜索引擎的识别分散问题的;此问题可通过301重定向来进行解决,具体在ASP.NET中可通过如下方法来处理:
1 private void CheckTopDomainName(HttpContext context)
2 {
3 Uri url = context.Request.Url;
4 string host = url.Host.ToLower();
5
6 int count = host.Split('.').Length;
7 bool doubleDomainName = host.EndsWith(".com.cn", StringComparison.CurrentCultureIgnoreCase) ||
8 host.EndsWith(".net.cn", StringComparison.CurrentCultureIgnoreCase) ||
9 host.EndsWith(".gov.cn", StringComparison.CurrentCultureIgnoreCase) ||
10 host.EndsWith(".org.cn", StringComparison.CurrentCultureIgnoreCase);
11
12 if (count == 2 || (count == 3 && doubleDomainName))
13 {
14 context.Response.Status = "301 Moved Permanently";
15 // 避免替换掉后面的参数中的域名
16 context.Response.AddHeader(
17 "Location",
18 url.AbsoluteUri.Replace(
19 string.Format("http://{0}", host),
20 string.Format("http://www.{0}", host)
21 )
22 );
23 }
2 {
3 Uri url = context.Request.Url;
4 string host = url.Host.ToLower();
5
6 int count = host.Split('.').Length;
7 bool doubleDomainName = host.EndsWith(".com.cn", StringComparison.CurrentCultureIgnoreCase) ||
8 host.EndsWith(".net.cn", StringComparison.CurrentCultureIgnoreCase) ||
9 host.EndsWith(".gov.cn", StringComparison.CurrentCultureIgnoreCase) ||
10 host.EndsWith(".org.cn", StringComparison.CurrentCultureIgnoreCase);
11
12 if (count == 2 || (count == 3 && doubleDomainName))
13 {
14 context.Response.Status = "301 Moved Permanently";
15 // 避免替换掉后面的参数中的域名
16 context.Response.AddHeader(
17 "Location",
18 url.AbsoluteUri.Replace(
19 string.Format("http://{0}", host),
20 string.Format("http://www.{0}", host)
21 )
22 );
23 }
24 }