Question

Within an ASP.Net project, for the release build's Web.Config (using a Web.Release.Config transform file), how do you inject a canonical url rule in the rewrite section?

Was it helpful?

Solution

Below is an example that worked for me, you have to use an XPath selector in order to inject your rule into the proper position via the xdt:Transform property.

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="CanonicalHostNameRule1" enabled="true" stopProcessing="true" 
                    xdt:Transform="InsertBefore(/configuration/system.webServer/rewrite/rules/rule[position() = 1])"
                >
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTP_HOST}" negate="true" pattern="^www\.yoursite\.com$" />
                    </conditions>
                    <action type="Redirect" url="http://www.yoursite.com/{R:1}" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

You can do some other interesting replacements using xpath statements as well. I hope the above example is helpful as StackOverflow is generally where I look first for this type of thing these days.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top