在web.config中使用尾随斜杠301重定向的非www(单个重定向)

时间:2015-07-13 11:18:16

标签: c# asp.net url-rewriting web-config

如何通过单个301重定向(避免重定向链)301将我的网址重定向到non-www equivalent with trailing slash?我正在使用ASP.net 4.5 / C#/ Web Project,我的路由在RouteConfig.cs

中注册

一个选项是检查每个页面后面的代码中的URL并重建URL,但我更喜欢让IIS使用重写规则来处理它。

从这张图片中可以看到(通过chrome,客户端),有两个301重定向,因为在我的web.config中我有两个规则,一个用于更改为小写URL,另一个用于添加尾部斜杠。

enter image description here

可能在IIS中有一个选项可以防止重定向,直到所有URL重写都在内部运行。我搜索了它,但还没找到解决方案。

1 个答案:

答案 0 :(得分:3)

在web.config中(您需要安装IIS URL重写模块)

   <system.webServer>
        <rewrite>
            <rules>
                <rule name="noslash" patternSyntax="ECMAScript" stopProcessing="true">
                    <match url=".+[^\/]$" />
                    <conditions logicalGrouping="MatchAny">
                        <add input="{HTTP_HOST}" pattern="www.yourdomain.com" />
                        <add input="{HTTP_HOST}" pattern="yourdomain.com" />
                    </conditions>
                    <action type="Redirect" url="http://yourdomain.com/{R:0}/" />
                </rule>
                <rule name="www" patternSyntax="ECMAScript" stopProcessing="true">
                    <match url=".+\/$" />
                    <conditions logicalGrouping="MatchAny">
                        <add input="{HTTP_HOST}" pattern="www.yourdomain.com" />
                    </conditions>
                    <action type="Redirect" url="http://yourdomain.com/{R:0}" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>

EDIT2:如果网址不存在,则在网址末尾添加尾部斜杠

相关问题