Borbin the 🐱

IIS - redirect subdomain to a directory

05 February, 2013


Here is how to redirect a subdomain to a directory using the rewrite rule in IIS. For example, if you like to have subdomain.mysite.com/ point to mysite.com/subdomain/, you simply add the following domain-rewrite rule to web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="domain-rewrite">
          <!--
           subdomain.mysite.com/dir/index.html?abc -> mysite.com/subdomain/dir/index.html?abc
          -->
          <match url=".*" />
          <!-- {R:0} = dir/index.html -->
          <conditions>
            <!-- subdomain is the first capture '(.*)' = {C:1} -->
            <add input="{HTTP_HOST}" pattern="^(?!www)(.*)\.mysite\.com$" />
          </conditions>
          <action type="Rewrite" url="{C:1}/{R:0}" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>