How to share cookie between domain and subdomain, but not other subdomains

I'd recommend forcing the use of the www. version of the site, for this reason amongst others, this site has excellent reasons why...

http://www.yes-www.org/why-use-www/

To do this in .net you can add the following to your web.config

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Redirect to www" stopProcessing="true">
        <match url="(.*)" />
        <conditions trackAllCaptures="false">
        <add input="{HTTP_HOST}" pattern="^sitename.com$" />
        </conditions>
        <action type="Redirect" url="{MapProtocol:{HTTPS}}://www.{HTTP_HOST}{HTTP_URL}" redirectType="Permanent"/>
      </rule>
    </rules>
    <rewriteMaps>
      <rewriteMap name="MapProtocol">
        <add key="on" value="https" />
        <add key="off" value="http" />
      </rewriteMap>
    </rewriteMaps>
  </rewrite>
</system.webServer>

This will auto-redirect permanently (see the addition of redirectType="Permanent") for non-www URLs to the www equivalent and retain the HTTP(s) protocol.

The trackAllCaptures part is related to the regex pattern matching - in our case we do not need to capture anything; we only need to match for the rule, so we can leave as false.

The regex pattern ^sitename.com$ will match when the hostname matches exactly to "sitename.com" - the ^ means the start position and the $ means the end position

The rewrite map is from an idea from Jeff Graves I believe, http://jeffgraves.me/2012/11/06/maintain-protocol-in-url-rewrite-rules/

The way I have shown shows just one way to do this, like with most things - there are multiple ways on achieving this.

Scott Forsyth has an article on a different way of achieving this too (also references Jeff Graves) http://weblogs.asp.net/owscott/url-rewrite-protocol-http-https-in-the-action


You can avoid this problem by redirecting your non www domain to www with UrlRewrite module in >IIS7

rewrite rule to put into web.config

<system.webServer>
<rewrite>
    <rules>
      <rule name="Redirect to WWW" stopProcessing="true">
        <match url=".*" />
        <conditions>
          <add input="{HTTP_HOST}" pattern="^example.com$" />
        </conditions>
        <action type="Redirect" url="http://www.example.com/{R:0}"
             redirectType="Permanent" />
      </rule>
        </rules>
    </rewrite>
</system.webServer>