通过web配置的规范错误(作为非www到www)

时间:2013-08-01 05:31:16

标签: asp.net web-config

我有一个面临规范问题的网站。我希望我的网站从非www移动到www当我输入我的网址例如abc.com到www.abc.com.i得到了一个代码但它是不工作。

  <rewrite>
 <rules>
   <rule name="RedirectToWWW" enabled="true" stopProcessing="true">
  <match url=".*" />
  <conditions>
    <add input="{HTTP_HOST}" pattern="^(?!www)(\S+)\.com$" />
   </conditions>
  <action type="Redirect" url="http://www.{C:0}/{R:0}" />
   </rule>
  </rules>
</rewrite>

错误是: 重写不属于system.webServer

1 个答案:

答案 0 :(得分:1)

您可能会考虑采用不同的方法:

protected void Application_BeginRequest (object sender, EventArgs e)
{
 if (!Request.Url.Host.StartsWith ("www") && !Request.Url.IsLoopback)
 {
  UriBuilder builder = new UriBuilder (Request.Url);
  builder.Host = "www." + Request.Url.Host;
  Response.Redirect (builder.ToString (), true);
 }
}

然而,这将进行302重定向,因此建议稍微调整一下:

protected void Application_BeginRequest (object sender, EventArgs e)
{ 
 if (!Request.Url.Host.StartsWith ("www") && !Request.Url.IsLoopback)
 {
  UriBuilder builder = new UriBuilder (Request.Url);
  builder.Host = "www." + Request.Url.Host;
  Response.StatusCode = 301;
  Response.AddHeader ("Location", builder.ToString ());
  Response.End ();
 }
}

这个将返回301 Moved Permanently。

如果您想在 web.config 中添加,请点击此链接http://weblogs.asp.net/owscott/archive/2009/11/27/iis-url-rewrite-rewriting-non-www-to-www.aspx