如何使用&QUOT重定向; WWW" URL的未经" WWW"网址或反之亦然? [英] How to redirect with "www" URL's to without "www" URL's or vice-versa?

查看:625
本文介绍了如何使用&QUOT重定向; WWW" URL的未经" WWW"网址或反之亦然?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET 2.0 C#。我想重定向为我用www的Web应用程序的所有请求,没有WWW

I am using ASP.NET 2.0 C#. I want to redirect all request for my web app with "www" to without "www"

www.example.com改为example.com

www.example.com to example.com

或者

example.com到www.example.com

example.com to www.example.com

Stackoverflow.com已经在这样做,我知道有在PHP(的.htaccess)文件中的premade机制。但如何做它在asp.net?

Stackoverflow.com is already doing this, I know there is a premade mechanism in PHP (.htaccess) file. But how to do it in asp.net ?

感谢

推荐答案

我已经在过去的以下解决方案时,我没有去过能够修改IIS设置。

I've gone with the following solution in the past when I've not been able to modify IIS settings.

无论是在一个HttpModule(可能是干净的),或在的global.asax.cs或的Application_BeginRequest一些的BasePage类型的事件,比如我OnInit的执行针对所请求的URL检查,一个已知的字符串我想使用:

Either in an HTTPModule (probably cleanest), or global.asax.cs in Application_BeginRequest or in some BasePage type event, such as OnInit I perform a check against the requested url, with a known string I wish to be using:

public class SeoUrls : IHttpModule
{
  #region IHttpModule Members

  public void Init(HttpApplication context)
  {
      context.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
  }

  public void Dispose()
  {
  }

  #endregion

  private void OnPreRequestHandlerExecute(object sender, EventArgs e)
  {
    HttpContext ctx = ((HttpApplication) sender).Context;
    IHttpHandler handler = ctx.Handler;

    // Only worry about redirecting pages at this point
    // static files might be coming from a different domain
    if (handler is Page)
    {
      if (Ctx.Request.Url.Host != WebConfigurationManager.AppSettings["FullHost"])
      {
        UriBuilder uri = new UriBuilder(ctx.Request.Url);

        uri.Host = WebConfigurationManager.AppSettings["FullHost"];

        // Perform a permanent redirect - I've generally implemented this as an 
        // extension method so I can use Response.PermanentRedirect(uri)
        // but expanded here for obviousness:
        response.AddHeader("Location", uri);
        response.StatusCode = 301;
        response.StatusDescription = "Moved Permanently";
        response.End();
      }
    }
  }
}

然后在你的web.config中注册类:

Then register the class in your web.config:

<httpModules>
  [...]
  <add type="[Namespace.]SeoUrls, [AssemblyName], [Version=x.x.x.x, Culture=neutral, PublicKeyToken=933d439bb833333a]" name="SeoUrls"/>
</httpModules>

此方法效果相当好适合我们。

This method works quite well for us.

这篇关于如何使用&QUOT重定向; WWW&QUOT; URL的未经&QUOT; WWW&QUOT;网址或反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆