views:

731

answers:

3

Is there any way to set a cookie that is not readable on subdomains? In other words, have the cookie available on domain.com, but not www.domain.com or xyz.domain.com.

//this is what i'm "intending"...
setcookie($name,$value,$expires,'/','domain.com');
//however, this is how it behaves:
setcookie($name,$value,$expires,'/','.domain.com');

The reasoning: I'm setting up a static CDN on a subdomain and don't want the user session cookies going back and forth for every image, css file, js file, etc.

...do I have to fall back to using www.domain.com for my site? Are there any workarounds?

+2  A: 

this is the reason why quite a few sites (including this one) register a dedicated domain for use as a CDN.

Rowland Shaw
Excellent +1
Thiyagaraj
+5  A: 

Apparently, having a cookie on "domain.com" that will match "*.domain.com" is expected behaviour.

For instance : PERSISTENT CLIENT STATE HTTP COOKIES state (some emphasis mine) :

domain=DOMAIN_NAME

When searching the cookie list for valid cookies, a comparison of the domain attributes of the cookie is made with the Internet domain name of the host from which the URL will be fetched. ...
"Tail matching" means that domain attribute is matched against the tail of the fully qualified domain name of the host. A domain attribute of "acme.com" would match host names "anvil.acme.com" as well as "shipping.crate.acme.com".

Only hosts within the specified domain can set a cookie for a domain and domains must have at least two (2) or three (3) periods in them to prevent domains of the form: ".com", ".edu", and "va.us". Any domain that fails within one of the seven special top level domains listed below only require two periods. Any other domain requires at least three. The seven special top level domains are: "COM", "EDU", "NET", "ORG", "GOV", "MIL", and "INT".

So, you'll either have to :

  • use "www.domain.com" for your site
  • or use a totally different domain name for your static content (like ".anotherdomain.com")
    • for instance, this is what is done on stackoverflow : static content is served from sstatic.net
Pascal MARTIN
Nice explanation, +1 here as well.
Thiyagaraj
Wow, great info. I didn't run across that when digging around. Thanks man. I guess this answers my question... www.domain.com it is.
brianreavis
You're welcome :-) Have fun ! (and, if using www.domain.com for your website and cookies, don't forget to make sure that "domain.com", when used to access your site, redirects to "www.domain.com" -- do not depending on the browser to do that automatically : it doesn't always work -- doesn't work behind a proxy, sometimes, for instance (that's the case where I work, and it's a pain))
Pascal MARTIN
A: 

It is not possible as the cookie domain is tail matched against the domain name. You will have to go with www.

Zed