PHP setcookie() 用于域但不用于子域
有没有办法设置在子域上不可读的cookie?换句话说,让 Cookie 在 domain.com
上可用,但不在 www.domain.com
或 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');
推理:我正在子域上设置静态 CDN,并且不希望用户会话 cookie 来回处理每个图像、css 文件、js 文件等
...我是否必须回退到使用www.domain.com
适合我的网站吗?有什么解决方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
显然,在“domain.com”上有一个与“*.domain.com”匹配的 cookie 是预期的行为。
例如:持久客户端状态 HTTP COOKIES 状态(有些是我的强调):
因此,您必须:
www.domain.com
”,.anotherdomain.com
”)代码>”)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) :
So, you'll either have to :
www.domain.com
" for your site.anotherdomain.com
")这就是为什么相当多的网站(包括这个网站)注册专用域名用作 CDN 的原因。
this is the reason why quite a few sites (including this one) register a dedicated domain for use as a CDN.
当然可以!这就是大多数网站所做的。甚至内置的 php 函数
session_start()
也能做到这一点。它的 Set-Cookie http 响应标头看起来就像这样简单:根据 RFC 6265,第 4.1.2.3 节,该段落中的最后一条语句:
因此,您所要做的就是在从
domain.com
设置 cookie 时省略域属性。为了进一步确认,我自己测试了它,我可以向您保证,cookie 无法从当您设置子域并忽略域属性时。
Of cource you can! That's what most websites do. Even the built-in php function
session_start()
does that. and its Set-Cookie http response header looks just as simple as this:According to RFC 6265, section 4.1.2.3, the last statement in the paragraph:
So, all you have to do is to omit the domain attribute while setting the cookie from your
domain.com
For further confirmation, I tested it myself, and I can assure you, cookies aren't accessible from subdomains when you set 'em while omitting the domain attribute.
这是不可能的,因为 cookie 域与域名尾部匹配。你必须使用www。
It is not possible as the cookie domain is tail matched against the domain name. You will have to go with www.