如何通过IIS7中的URL重写强制example.com重定向到www.example.com?什么样的规则应该进入web.config?感谢。
答案 0 :(得分:28)
这是Microsoft的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>
答案 1 :(得分:28)
为了使其更通用,您可以使用以下适用于任何域的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>
答案 2 :(得分:3)
不确定最好的方法,但我有一个网站,其中包含运行此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>
似乎已完成工作。
答案 3 :(得分:0)
我不确定这是否有帮助,但我选择在应用级别执行此操作。这是我写的一个快速动作过滤器。只需在项目中的某处添加类,然后就可以将[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
{
..
..
}
希望有人帮助。干杯!