如何使用“www"重定向不带“www"的 URLURL 或反之亦然? [英] How to redirect with "www" URL's to without "www" URL's or vice-versa?
问题描述
我使用的是 ASP.NET 2.0 C#.我想将带有www"的网络应用的所有请求重定向到不带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) 文件中有一个预制机制.但是如何在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(可能是最干净的)中,还是在 Application_BeginRequest 中的 global.asax.cs 中,或者在某些 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.
这篇关于如何使用“www"重定向不带“www"的 URLURL 或反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!