Search code examples
iisurl-rewrite-moduleweb.config-transform

Web.config Transform: Optionally Insert Parent Nodes of Node You Want to Insert or Patch


Documenting this for others since I figured it out and couldn't find it anywhere else:

Issue/Goal:
You are trying to insert a node into the web.config using transforms, but are getting an error when packaging/previewing it or are seeing the node that you want to insert inserted multiple times.


Solution

  • Solution:
    You need to create the parent nodes of that node first since they probably do not exist. That way you are ensuring that they exist without just ignoring other entries there if they do exist as some solutions do with a Remove option.

    Here is an example that I've recently created and tested:

    <system.webServer>
    <!-- Creates the rewrite node if it does not exist yet (ensures it exists) -->
        <rewrite xdt:Transform="InsertIfMissing"/>
    <!-- Creates the rules node inside the rewrite node if it does not exist yet -->
        <rewrite>
            <rules xdt:Transform="InsertIfMissing"/>
        </rewrite>
    <!-- Inserts the new rule inside the rewrite/rules path -->
        <rewrite>
            <rules>
                <rule name="subdomain.domain.com Redirect" stopProcessing="false" xdt:Transform="Insert">
                    <match url="^$"/>
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="subdomain.domain.com"/>
                    </conditions>
                    <action type="Redirect" redirectType="Permanent" url="http://domain.com/alias"/>
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
    

    I hope you find this helpful!