之前是做301定向是在每个页面调用一个方法的,原文http://www.cnblogs.com/hakuci/archive/2010/11/19/1881681.html
现在利用Web.config的HttpModule 实现整站301永久重定向
具体方法如下:
1在web.config加入配置
<configuration>
<appSettings>
<add key="WebDomain" value="wecanwecan.com"/>
<add key="URL301Location" value="www.wecanwecan.com"/>
</appSettings>
2,在当前解决方案下新建一个类库项目
3,新建一个cs,我这里粗陋的命名一下:ChangeDomain.cs
using System;
using System.Web;
using System.Configuration;
namespace ChangeDomain
{
public class RedirectNewDomain : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.AuthorizeRequest += (new EventHandler(Process301));
}
public void Process301(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
HttpRequest request = app.Context.Request;
string lRequestedPath = request.Url.DnsSafeHost.ToString();
string strDomainURL = ConfigurationManager.AppSettings["WebDomain"].ToString();
string strWebURL = ConfigurationManager.AppSettings["URL301Location"].ToString();
if (lRequestedPath.IndexOf(strWebURL) == -1)
{
app.Response.StatusCode = 301;
app.Response.AddHeader("Location", lRequestedPath.Replace(lRequestedPath, "http://" + strWebURL + request.RawUrl.ToString().Trim())); //这里面的域名根据自己的实际情况修改
app.Response.End();
}
}
}
}
写完这个基本就ok了。剩下的就是在web.config里注册一下就好了。
<httpModules>
<add name="ChangeDomain" type="ChangeDomain.RedirectNewDomain, ChangeDomain" />
</httpModules>
<add name="随便命名" type="HttpModule命名空间加类名,dll文件名" />