代码之家  ›  专栏  ›  技术社区  ›  Anwar Chandra

IIS 6如何从http://example.com/*重定向到http://www.example.com/*

  •  4
  • Anwar Chandra  · 技术社区  · 16 年前

    我正在使用ASP.NET 3.5和IIS 6。

    我们如何自动重定向网页 http(s)://example.com/* http(s)://www.example.com/* 是吗?

    谢谢。

    4 回复  |  直到 16 年前
        1
  •  6
  •   Zhaph - Ben Duguid    16 年前

    我用一个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中:

    查找分区 <httpModules> <system.web> 第节,它可能已经有了一些其他条目,并添加了如下内容:

    <add name="SeoModule" type="MySite.Classes.SeoModule, MySite" />
    

    您可以在这里看到这一点:

    一切都结束了 http://www.doodle.co.uk

        2
  •  0
  •   Chris Arnold    16 年前

    这个 MSDN page 也许会帮助你。

        3
  •  0
  •   RickNZ    16 年前

    一般来说,如果让IIS处理重定向,性能会更好。为此,请创建一个主机头设置为example.com的新网站,并使用IIS管理器配置重定向。

        4
  •  -2
  •   tooshel    16 年前

    我觉得最好用DNS。