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

孤人 提交于 2019-11-28 01:39:14

问题


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.


回答1:


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:

  • http://doodle.co.uk
  • http://doodlegraphics.co.uk
  • http://www.doodle-graphics.co.uk

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




回答2:


This MSDN page might help you.




回答3:


In general, the performance will be better if you let IIS handle the redirection. To do that, create a new web site with the host header set to example.com, and use IIS Manager to configure the redirection.




回答4:


I think that's best done with DNS.



来源:https://stackoverflow.com/questions/1872227/iis-6-how-to-redirect-from-http-example-com-to-http-www-example-com

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!