If you set a cookie like this:
then the cookie will only apply to the request domain, and will only be sent for requests to the exact same domain, not any other subdomains. (See What is a host only cookie?)
Two different domains (e.g.
sub2.example.com) can only share cookies if the
domain attribute is present in the header:
Set-Cookie: name=value; domain=example.com
The domain attribute must “domain-match” the request URL for it to be valid, which basically means it must be the request domain or a super-domain. So this applies for both examples in the question, as well as sharing between two separate subdomains.
This cookie would then be sent for any subdomain of
example.com, including nested subdomains like
subsub.subdomain.example.com. (Bear in mind there are other attributes that could restrict the scope of the cookie and when it gets sent by the browser, like
Because of the way the domain-matching works, if you want
sub2.example.com to share cookies, then you’ll also share them with
- www vs no-www and cookies
- setcookie.net: a site where you can try it out
A note on leading dots in
domain attributes: In the early RFC 2109, only domains with a leading dot (
domain=.example.com) could be used across subdomains. But this could not be shared with the top-level domain, so what you ask was not possible in the older spec.
However, the newer specification RFC 6265 ignores any leading dot, meaning you can use the cookie on subdomains as well as the top-level domain.