如何使用IIS7中的URL重写来强制将example.com重定向到www.example.com?应该在web.config中添加什么样的规则?谢谢。
为了使其更加通用,您可以使用以下URL重写规则,适用于任何域名:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Add WWW" stopProcessing="true">
<match url="^(.*)$" />
<conditions>
<add input="{HTTP_HOST}" pattern="^(?!www\.)(.*)$" />
</conditions>
<action type="Redirect" url="http://www.{C:0}{PATH_INFO}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
</system.webServer>
stopProcessing="true"
? - serge/*contact* => /contact-us
,那么在这种情况下,此规则将不会被处理。 - serge这是微软关于URL Rewrite Module 2.0的示例,将*.fabrikam.com重定向到www.fabrikam.com。
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Add www" patternSyntax="Wildcard" stopProcessing="true">
<match url="*" />
<conditions>
<add input="{HTTP_HOST}" pattern="www.fabrikam.com" negate="true" />
</conditions>
<action type="Redirect" url="http://www.fabrikam.com/{R:1}" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
虽然不确定最佳实践是什么,但我有一个网站,其中所有旧域名/子域名都在运行此web.config文件:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Transfer" stopProcessing="true">
<match url=".*" />
<action type="Redirect" url="http://www.targetsite.com/{R:0}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
看起来完成了工作。
我不确定这是否有所帮助,但我选择在应用程序级别执行此操作。以下是我编写的一个快速操作过滤器... 只需在项目中添加该类,然后您可以将[RequiresWwww]添加到单个操作或整个控制器。
public class RequiresWww : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpRequestBase req = filterContext.HttpContext.Request;
HttpResponseBase res = filterContext.HttpContext.Response;
//IsLocal and IsLoopback i'm not too sure on the differences here, but I have both to eliminate local dev conditions.
if (!req.IsLocal && !req.Url.Host.StartsWith("www") && !req.Url.IsLoopback)
{
var builder = new UriBuilder(req.Url)
{
Host = "www." + req.Url.Host
};
res.Redirect(builder.Uri.ToString());
}
base.OnActionExecuting(filterContext);
}
}
然后
[RequiresWwww]
public ActionResult AGreatAction()
{
...
}
或者
[RequiresWwww]
public class HomeController : BaseAppController
{
..
..
}
example.com
的虚拟主机,然后通过简单的‘HTTP重定向’将其重定向到http://www.example.com/
(使用301状态码,并且不选择‘精确目标’选项,以保持路径不变)。 - bobince