简体   繁体   中英

non-www with trailing slash 301 redirect in web.config (Single Redirect)

How can I 301 redirect my URLs to non-www equivalent with trailing slash at the end with only a single 301 redirect (avoid redirect chain)? I am using ASP.net 4.5 / C# / Web Project with my routes registered in the RouteConfig.cs .

One option is to check the URL in code behind for each page and rebuild the URL, but I prefer letting IIS handle it using Rewrite rules.

As you can see from this image (via chrome, client side), there are two 301 redirects, because in my web.config I have two rules, one for changing to lowercase URL and second to add trailing slash.

在此处输入图片说明

Maybe there is an option in IIS to prevent redirection until all the URL rewrites ran internally. I searched for it, but couldn't find a solution yet.

In web.config (you need to have IIS URL Rewrite module installed)

   <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: added trailing slash at the end of the url if it doesn't exist

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM