将所有裸域 url 重定向到保留 url 的子域 (www) url,除了 IIS/ASP.NET 上的一页

Siv*_*ula 5 iis httpmodule asp.net-4.0 iis-7.5

实现上述目标的最佳方法是什么?我知道它可以在 HttpModule 级别实现。是否可以仅通过 web.config(更容易和更快地执行代码)。

Mar*_*urg 5

通过 web.config 使用 URL 重写模块很容易做到这一点:

<rewrite>
    <rules>
        <clear />
        <rule name="Redirect naked domains to www.domain.com" stopProcessing="true">
            <match url="(.*)" />
            <conditions logicalGrouping="MatchAll">
                <add input="{HTTP_HOST}" negate="true" pattern="^www\." />
                <add input="{REQUEST_URI}" negate="true" pattern="^noredirect/forthis/page\.aspx$" />
                <add input="{REQUEST_URI}" negate="true" pattern="^noredirect/forthis/page-as-well\.aspx$" />
                <add input="{REQUEST_URI}" negate="true" pattern="^noredirect/forthis/page-as-well-too\.aspx$" />
            </conditions>
            <action type="Redirect" url="http://www.{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" redirectType="Permanent" />
        </rule>
    </rules>
</rewrite>
Run Code Online (Sandbox Code Playgroud)

或者如果你真的只有一个不需要重定向的页面,它甚至可以缩短为:

<rewrite>
    <rules>
        <clear />
        <rule name="Redirect naked domains to www.domain.com" stopProcessing="true">
            <match url="^noredirect/forthis/page\.aspx$" negate="true" />
            <conditions logicalGrouping="MatchAll">
                <add input="{HTTP_HOST}" negate="true" pattern="^www\." />
            </conditions>
            <action type="Redirect" url="http://www.{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" redirectType="Permanent" />
        </rule>
    </rules>
</rewrite>
Run Code Online (Sandbox Code Playgroud)