Setting up URL Rewrite rule for a specific domain

Matt Roberts picture Matt Roberts · Jun 12, 2013 · Viewed 21.5k times · Source

For local dev testing, I need to catch all requests to www.somedomain.com/XXX (where X is the path), and send them on to localhost/somevdir/XXX.

I've added this to my HOSTS file (c:\windows\system32\drivers\etc):

127.0.0.1   www.mydomain.com

Then, in IIS8 (Windows 8), I've added a binding to my "Default Web Site" for the host www.mydomain.com. This works, I can now browse www.mydomain.com/test.html and see a test html page. My virtual dir is inside the Default web site. I then add a URL Rewrite URL to the web site for the last bit:

<rewrite>
    <rules>
        <rule name="mydomain.com" stopProcessing="true">
            <match url="^www.mydomain.com/(.*)" />
            <action type="Rewrite" url="localhost/MyVDir/{R:1}" logRewrittenUrl="true" />
        </rule>
    </rules>
</rewrite>

But - that doesn't work. I get a 404 so it looks the the match never happens. I've tried redirect and rewrite, and I've tried without the ^ in the regex and a few other regex tweaks. Can someone explain what I've done wrong?

Answer

Martin Steel picture Martin Steel · Jun 12, 2013

I think the following should work:

<rule name="mydomain.com" stopProcessing="true">
    <match url="(.*)" />
    <conditions logicalGrouping="MatchAll">
        <add input="{HTTP_HOST}" pattern="^(mydomain\.com|www\.mydomain\.com)$" />
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    </conditions>
    <action type="Redirect" url="http://localhost/MyVDir/{R:1}" redirectType="Temporary" />
</rule>

The match on any URL makes sure the conditions are checked, and the HTTP_HOST server variable seems the most reliable way of checking the requested hostname. You could remove the REQUEST_FILENAME input condition, but it works as quite a nice sanity check to make sure static files are always served.