Just set the domain
and path
attributes on your cookie, like:
<script type="text/javascript">
var cookieName = 'HelloWorld';
var cookieValue = 'HelloWorld';
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + cookieValue + ";expires=" + myDate
+ ";domain=.example.com;path=/";
</script>
Two different domains (e.g. mydomain.com
and subdomain.mydomain.com
, or sub1.mydomain.com
and sub2.mydomain.com
) can only share cookies if the domain is explicitly named in the Set-Cookie
header. Otherwise, the scope of the cookie is restricted to the request host. (This is referred to as a "host-only cookie". See What is a host only cookie?)
For instance, if you sent the following header from subdomain.mydomain.com
, then the cookie would only be sent for requests to that domain, and won't be sent for requests to any other domains:
Set-Cookie: name=value
However if you use the following, it will be usable on both domains:
Set-Cookie: name=value; domain=mydomain.com
This cookie will be sent for any subdomain of mydomain.com, including nested subdomains like subsub.subdomain.mydomain.com
.
In RFC 2109, a domain without a leading dot meant that it could not be used on subdomains, and only a leading dot (.mydomain.com
) would allow it to be used across multiple subdomains (but not the top-level domain, so what you ask was not possible in the older spec).
However, all modern browsers respect the newer specification RFC 6265, and will ignore any leading dot, meaning you can use the cookie on subdomains as well as the top-level domain.
In summary, if you set a cookie like the second example above from mydomain.com
, it would be accessible by subdomain.mydomain.com
, and vice versa. This can also be used to allow sub1.mydomain.com
and sub2.mydomain.com
to share cookies.
See also:
Best Answer
If you do:
config.action_controller.session[:domain] = '.YOURDOMAIN.COM'
in your production.rb file, that will allow you to have everyone logged in on all subdomains of your subdomain. If you then add a filter (or whatever, but I use a filter so I know that works) that checks that someone is actually using the right domain before you show controller stuff, it works pretty well.
As an example, you could store the appropriate subdomain for the session as a session variable and give people link options to their specific things if they were on your main domain or looking at a page on someone else's subdomain.
This seems to be the general pattern for doing this sort of thing -- if you set a cookie specific to the subdomain otherwise you won't be able to tell when they've logged in to the main site. I also have a '
users_domain?
' helper that ends up getting called occasionally in views when I do this.If you don't want to have those sorts of common web design patterns, wesgarrion's single use -> session creation on subdomain is also a way to go. I just thought I'd mention this as a design / interaction / code issue.