0

After reading this Share cookie between subdomain and domain, I still don't completely understand. My task is share the cookies between the domain and its subdomain. They both can install them:

  1. If sub1.domain.com installs them first, then they should be accessible in both sub1.domain.com and domain.com

  2. And if domain.com installs them first, then they should be accessible in both sub1.domain.com and domain.com

By installing first I mean, they get installed once a new user comes to either the main domain or subdomain.

So if I install them as Set-Cookie: name=value; domain=example.com on any of those domains, will they be shared?

Community
  • 1
  • 1
アレックス
  • 24,309
  • 37
  • 129
  • 229
  • 1
    Yes, per the information in the SO link in your question. Using the root domain when setting a cookie from either domain will make it accessible to both the root and sub-domains. – musicfuel Dec 21 '14 at 13:27

2 Answers2

1

Yes, they will be shared. Here's how the domain matching works (quoting the RFC):

A string domain-matches a given domain string if at least one of the following conditions hold:

  • The domain string and the string are identical. (Note that both the domain string and the string will have been canonicalized to lower case at this point.)
  • All of the following conditions hold:
    • The domain string is a suffix of the string.
    • The last character of the string that is not included in the domain string is a %x2E (".") character.
    • The string is a host name (i.e., not an IP address).

So, for cookie domain set to example.com, both example.com and subdomain.example.com will successfully match:

  • for the first one, it's the same domain string - example.com, so the first condition is met
  • for the second one, the second condition is met:
    • example.com is a suffix of subdomain.example.com
    • the last character of the rest of the string - subdomain. - is . apparently
    • subdomain.example.com is definitely a host name, not an IP
raina77ow
  • 91,589
  • 12
  • 180
  • 210
-1

You need to prepend a . to the domain nam. Eg: Set-Cookie: name=value; domain=.example.com, which will make the cookie carry across example.com and anything.example.com.

Fizzadar
  • 361
  • 3
  • 10
  • 1
    Modern browsers no longer require the leading dot to carry it across domains. This still works, but both the leading dot and without should have the same result. – musicfuel Dec 21 '14 at 13:25