Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
792 views
in Technique[技术] by (71.8m points)

asp.net - IIS 6 how to redirect from http://example.com/* to http://www.example.com/*

I am using asp.net 3.5 and IIS 6.

How can we automatically redirect pages from http(s)://example.com/* to http(s)://www.example.com/* ?

thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I did this with an 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();
        }
      }
    }
  }
}

Then we need to add the module to our Web.Config:

Find the section <httpModules> in the <system.web> section, it may well have a couple of other entries in there already, and add something like:

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

You can see this in action here:

All end up on http://www.doodle.co.uk


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...