Search code examples
c#asp.netweb-confighttp-redirect

.NET: Redirect from domain and subfolder to new domain, retaining path and querystring, using httpredirect in web.config


I am trying to setup a domain redirect as part of a domain migration. My caveat is that the site I am redirecting from is in a subfolder of a wider domain. I also need to retain the rest of the path and query string.

I need to setup a redirect in web.config that achieves the following:

I've tried:

<httpRedirect enabled="true" destination="https://www.domain1.com$V$Q" httpResponseStatus="Temporary" exactDestination="true" />

but this doesn't remove the "mysite" subfolder. It redirects to https://www.domain2.com/mysite instead of https://www.domain2.com

I've also tried creating a rewrite rule but I cannot figure out a working input and regex.

TIA.


Solution

  • You could go with two rules in URL Rewrite:

    <rule name="remove-my-site">
      <match url="^mysite/([/_0-9a-z-]+)"/>
      <action type="Rewrite" url="{R:1}"/>
    </rule>
    <rule name="domain1-to-domain2">
        <match url=".*" />
        <conditions logicalGrouping="MatchAny">
            <add input="{HTTP_HOST}" pattern="domain1.com" />
        </conditions>
        <action type="Redirect" url="http://www.domain2.com/{R:0}" />
    </rule>
    

    You will not make it with httpRedirect. It's for much simple re-writes.

    You can also check Application Request Routing documentation for configuring a reverse router with IIS.

    What we might have missed is this step:

    Enabling Reverse Proxy functionality