Redirect Non-WWW to WWW (except one spesific subdomain)

1.1k Views Asked by At

On my Windows 2012 server I have installed the URL Rewrite module in IIS. I have followed this guide to redirect non-www to www in web.config: http://www.surfingsuccess.com/asp/iis-url-rewrite.html#.VF6GBid0yAU

So far, so good!

The only problem is that we also host the subdomain "api.example.com". This API stops working when I apply the code in web.config.

My question is: What is wrong with the code below? Why does the subdomain stop working when I try to redirect non-www to www, except "api.example.com"?

    <rewrite>
        <rules>
            <rule name="CanonicalHostNameRule1">
                <match url="(.*)" />
                <conditions>
                    <add input="{HTTP_HOST}" pattern="^www\.example\.com$" negate="true" />
                    <add input="{HTTP_HOST}" pattern="^api\.example\.com$" negate="true" />
                </conditions>
                <action type="Redirect" url="http://www.example.com/{R:1}" />
            </rule>
        </rules>
    </rewrite>
2

There are 2 best solutions below

5
On

I have similar check and I have same rule but have specified differently in pattern.

My suggestion is to enable Failed request tracing to check URL rewrites. http://www.iis.net/learn/extensions/url-rewrite-module/using-failed-request-tracing-to-trace-rewrite-rules

Edit: Updated rule.

 <rewrite>
            <rules>
                <rule name="non-root" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{HTTP_HOST}" pattern="^(www.example.com)$" negate="true" />
                        <add input="{HTTP_HOST}" pattern="^(api.example.com)$" negate="true" />
                        <add input="{HTTP_HOST}" pattern="^(example.com)$" />
                    </conditions>
                    <action type="Redirect" url="http://www.example.com/{R:1}" />
                </rule>
            </rules>
        </rewrite>
1
On

Actually, there was nothing wrong with my rewrite code. The reason why the API stopped working was because it had a referance to the top domain of the site (example.com), this caused a conflict with the rewrite code. After changing the referance to the www -version of the doman (www.example.com) everything worked fine.