URL Rewrite city.domain.com to domain.com/city

An IIS 7.x URL Rewrite question that comes up often is how to redirect something.domain.com to domain.com/city.

Here’s an example URL Rewrite rule to accomplish that:

<rule name="CName to URL" stopProcessing="true">
    <match url=".*" />
    <conditions>
        <add input="{HTTP_HOST}" pattern="^(?!www)(.*)\.domain\.com$" />
    </conditions>
    <action type="Redirect" url="http://domain.com/{C:1}/{R:0}" />
</rule> 

This will redirect http://anything_except_www.domain.com to http://domain.com/anything_except_www.

It will also maintain the URL and querystring, so http://subdomain.domain.com/aboutus?more=info will redirect to http://domain.com/subdomain/aboutus?more=info.

It’s also possible to do this with a rewrite rule instead so that the original URL is maintained while the server sees the rewritten path.  That rewrite rule will look like this:

<rule name="CName to URL - Rewrite" stopProcessing="true">
    <match url=".*" />
    <conditions>
        <add input="{HTTP_HOST}" pattern="^(?!www)(.*)\.domain\.com$" />
    </conditions>
    <action type="Rewrite" url="/{C:1}/{R:0}" />
</rule>   

Basically this rule will look like http://subdomain.domain.com/aboutus/ to the site visitor but it will really hit siteroot/subdomain/aboutus/ on the server.

Note that there are other considerations for rewrites which are covered in more depth here.

No Comments