Setting cookies for multiple sub-domains

13,618

Solution 1

Webpages can only set cookies for the second (or higher) level domain that they belong to.

This means that secure.example.com can read and set cookies for secure.example.com or .example.com, the latter of which can also be read and set by www.example.com

One last note: If the secure flag is set on a cookie, it can only be read and set over an https connection.

Solution 2

If you set the cookie domain to ".example.com", the cookie will work for all subdomains.

Share:
13,618
nilacqua
Author by

nilacqua

Updated on June 04, 2022

Comments

  • nilacqua
    nilacqua almost 2 years

    Is it possible to set a cookie for http://www.example.com from a PHP file located at https://secure.example.com? I have some code that was given to me, that appears to try and fails at this. I was wondering if this is possible at all.

  • nilacqua
    nilacqua about 14 years
    I wondering if I could be specific to which domains the cookie is sent to.
  • Piskvor left the building
    Piskvor left the building about 14 years
    @nilacqua: No. If the cookie is set for .example.com, it will be visible for any subdomain of example.com
  • louis.luo
    louis.luo over 11 years
    Hi @Powerlord, does that mean I can use the Javascript on secure.example.com to set a cookie for .example.com too? By just changing the value for document.cookie? Thx
  • Powerlord
    Powerlord over 11 years
    @Louis_PIG I don't have a lot of experience dealing with cookies in JavaScript. I would think you'd be able to do that, though... as I recall, it's part of the Cookie standard.
  • louis.luo
    louis.luo over 11 years
    Thanks @Powerlord . I am dealing with some problem like this, but your answer at least confirmed that this should be possible. Thanks!
  • Michael
    Michael about 6 years
    So if you own a.example and b.example.com but nothing else .example.com then this isn't a viable solution...
  • Matt
    Matt over 3 years
    Would this work for all subsub domains as well. Like would .example.com work on sub.example.com and sub.sub.example.com? Or would you have to do .sub.example.com to make that work?
  • zomars
    zomars over 2 years
    This won't work on www-less domains tho https://example.com