Search code examples
asp.netasp.net-mvcweb-config

How do I fix an invalid configuration error for a rewrite section in web.config


My web.config has the following rewrite element commented out on my machine, but when deployed to our QA server, it is not commented out. The difference between my machine and QA is that QA has an SSL certificate and my machine doesn't.

<system.webServer>
  <!--<rewrite>
    <rules>
      <clear/>
      <rule name="Redirect to https" stopProcessing="true">
        <match url=".*"/>
        <conditions>
          <add input="{HTTPS}" pattern="off" ignoreCase="true"/>
        </conditions>
        <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false"/>
      </rule>
    </rules>
  </rewrite>-->

When this is not commented out, I get a 500.19 error, invalid configuration? My question is, how do I get this rewrite to work on my machine? I guess installing a certificate is one part of the solution, but would like to know, if anything, what else I will have to do, in IIS etc. to get the project to run without this config element being commented out?


Solution

  • Take advantage of transforming the web.config

    enter image description here

    Reference: Transform web.config and additional resources to get a better understanding of how to apply the transformation.

    Include the <rewrite> element in the release config

    For example

    Web.Release.config

    <?xml version="1.0"?>
    <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
      <system.webServer>
        <rewrite xdt:Transform="Insert">
          <rules>
            <clear/>
            <rule name="Redirect to https" stopProcessing="true">
              <match url=".*"/>
              <conditions>
                <add input="{HTTPS}" pattern="off" ignoreCase="true"/>
              </conditions>
              <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false"/>
            </rule>
          </rules>
        </rewrite>
      </system.webServer>
    <configuration>
    

    and it will insert the <rewrite> element into the config file as part of the build process when the site is published (Release mode)

    The default version can be used as desired on your local machine where that element is not part of the main config file since it is only needed in release builds.

    Web.config

    <?xml version="1.0"?>
    <configuration>
      <connectionStrings>
        <!-- ... -->
      </connectionStrings>
      <system.web>
        <!-- ... -->
      </system.web>
    
      <!-- populated as desired, excluding the <rewrite> element -->
    </configuration>