【发布时间】:2009-12-09 07:37:48
【问题描述】:
我正在使用 asp.net 3.5 和 IIS 6。
我们如何自动将页面从http(s)://example.com/* 重定向到http(s)://www.example.com/*?
谢谢。
【问题讨论】:
我正在使用 asp.net 3.5 和 IIS 6。
我们如何自动将页面从http(s)://example.com/* 重定向到http(s)://www.example.com/*?
谢谢。
【问题讨论】:
我用 HttpModule 做到了这一点:
namespace MySite.Classes
{
public class SeoModule : IHttpModule
{
// As this is defined in DEV and Production, I store the host domain in
// the web.config: <add key="HostDomain" value="www.example.com" />
private readonly string m_Domain =
WebConfigurationManager.AppSettings["HostDomain"];
#region IHttpModule Members
public void Dispose()
{
//clean-up code here.
}
public void Init(HttpApplication context)
{
// We want this fire as every request starts.
context.BeginRequest += OnBeginRequest;
}
#endregion
private void OnBeginRequest(object source, EventArgs e)
{
var application = (HttpApplication) source;
HttpContext context = application.Context;
string host = context.Request.Url.Host;
if (!string.IsNullOrEmpty(m_Domain))
{
if (host != m_Domain)
{
// This will honour ports, SSL, querystrings, etc
string newUrl =
context.Request.Url.AbsoluteUri.Replace(host, m_Domain);
// We would prefer a permanent redirect, so need to generate
// the headers ourselves. Note that ASP.NET 4.0 will introduce
// Response.PermanentRedirect
context.Response.StatusCode = 301;
context.Response.StatusDescription = "Moved Permanently";
context.Response.RedirectLocation = newUrl;
context.Response.End();
}
}
}
}
}
然后我们需要将模块添加到我们的 Web.Config 中:
在<system.web> 部分中找到<httpModules> 部分,它可能已经有几个其他条目,并添加如下内容:
<add name="SeoModule" type="MySite.Classes.SeoModule, MySite" />
您可以在此处查看此操作:
【讨论】:
这个MSDN page 可能会对你有所帮助。
【讨论】:
一般来说,如果让 IIS 处理重定向,性能会更好。为此,请创建一个主机标头设置为 example.com 的新网站,并使用 IIS 管理器配置重定向。
【讨论】:
https://domain.com 重定向到https://www.domain.com - “另一个网站或目录”的重定向选项不允许在安全部分使用通配符(microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/…)。
我认为最好使用 DNS。
【讨论】: