Search code examples
url-rewritingasp.net-mvc-4iis-express

mvc 4 url rewrite is giving me a 404.4 even though the rewrite looks ok


I'm trying to get the url rewrite to change a request such as

http://foo.bar.com/

to

http://bar.com/foo/

I've popped in my URL rewrite rule to the web config like this

<rewrite>
  <rules>
      <rule name="SiteReWrite" stopProcessing="true">
          <match url="(.*)" />
          <action type="Rewrite" url="http://bar.com/{C:1}/"/>
          <conditions>
              <add input="{HTTP_HOST}" pattern="(.*)\.bar\.com" />
          </conditions>
      </rule>
  </rules>
</rewrite>

but I get a 404.4 error. Looking at the Trace Log File I see this in there

<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
 <System>
  <Provider Name="WWW Server" Guid="{3A2A4E84-4C21-4981-AE10-3FDA0D9B0F83}"/>
  <EventID>0</EventID>
  <Version>1</Version>
  <Level>4</Level>
  <Opcode>42</Opcode>
  <Keywords>0x0</Keywords>
  <TimeCreated SystemTime="2012-12-03T05:54:01.237Z"/>
  <Correlation ActivityID="{00000000-0000-0000-1000-0080030000FC}"/>
  <Execution ProcessID="7312" ThreadID="3180"/>
  <Computer>ULTRA</Computer>
 </System>
 <EventData>
  <Data Name="ContextId">{00000000-0000-0000-1000-0080030000FC}</Data>
  <Data Name="OldUrl">/</Data>
  <Data Name="NewUrl">http://bar.com/foo/</Data>
 </EventData>
 <RenderingInfo Culture="en-US">
  <Opcode>URL_CHANGED</Opcode>
 </RenderingInfo>
 <ExtendedTracingInfo xmlns="http://schemas.microsoft.com/win/2004/08/events/trace">
  <EventGuid>{D42CF7EF-DE92-473E-8B6C-621EA663113A}</EventGuid>
 </ExtendedTracingInfo>
</Event>

Which from the NewUrl looks like everything is peachy. Note, It looks like this instance was cached but I have seen the rule matches in the events previously.

If I enter the url http://bar.com/foo/ it works as it should. I don't want the user to see the new url, they should think that they are on foo.bar.com not bar.com/foo. That's just for some routing I have in the mvc app.

Does anyone have any idea why it's doing this odd behavior? I'm using IIS express 8 for this, I haven't tried with IIS yet.


Solution

  • Since I didn't want the user to see the url change I couldn't use the redirect. However what I should have mentioned is that all subdomains are going to the same site. Once I'd thought about it a bit more, and with a bit more reading on the rewrite module I modified an MSDN example like this; which works like a charm

    <rewrite>
      <rules>
        <rule name="Rewrite subdomain">
          <match url="(.*)" /> <!-- rule back-reference is captured here -->
          <conditions>
            <add input="{HTTP_HOST}" pattern="^([^.]+)\.bar\.com$" /> <!-- condition back-reference is captured here -->
          </conditions>
          <action type="Rewrite" url="{C:1}/{R:1}" /> <!-- rewrite action uses back-references to condition and to rule when rewriting the url -->
        </rule> 
      </rules>
    </rewrite>