Our ASP.NET MVC web application has a few different subdomains we use for testing and legacy code. The subdomains are:
We purposefully have the forms authentication not using domain level cookies because we want the cookies to be unique across these different subdomains. The problem is, when people get a link to the root domain (sitename.com), it requires them to log in again to get a cookie, even though they're already logged in to www.sitename.com.
Is there a way to share the cookie between only www.sitename.com and sitename.com without the other subdomains being affected?
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With