Share cookie between subdomain and domain
Share cookie between subdomain and domain
问题
I have two questions. I understand that if I specify the domain as .mydomain.com
(with the leading dot) in the cookie that all subdomains can share a cookie.
Can subdomain.mydomain.com
access a cookie created in mydomain.com
(without the www
subdomain)?
Can mydomain.com
(without the www
subdomain) access the cookie if created in subdomain.mydomain.com
?
回答
The 2 domains mydomain.com
and subdomain.mydomain.com
can only share cookies if the domain is explicitly named in the Set-Cookie
header. Otherwise, the scope of the cookie is restricted to the request host. (This is referred to as a "host-only cookie". See What is a host only cookie?)
For instance, if you sent the following header from subdomain.mydomain.com
, then the cookie won't be sent for requests to mydomain.com
:
Set-Cookie: name=value
However if you use the following, it will be usable on both domains:
Set-Cookie: name=value; domain=mydomain.com
This cookie will be sent for any subdomain of mydomain.com, including nested subdomains like subsub.subdomain.mydomain.com
.
In RFC 2109, a domain without a leading dot meant that it could not be used on subdomains, and only a leading dot (.mydomain.com
) would allow it to be used across multiple subdomains (but not the top-level domain, so what you ask was not possible in the older spec).
However, all modern browsers respect the newer specification RFC 6265, and will ignore any leading dot, meaning you can use the cookie on subdomains as well as the top-level domain.
In summary, if you set a cookie like the second example above from mydomain.com
, it would be accessible by subdomain.mydomain.com
, and vice versa. This can also be used to allow sub1.mydomain.com
and sub2.mydomain.com
to share cookies.
See also:
- www vs no-www and cookies
- cookies test script to try it out
在线测试cookie的生效问题
https://scripts.cmbuckley.co.uk/cookies.php
https://a.scripts.cmbuckley.co.uk/cookies.php
https://b.scripts.cmbuckley.co.uk/cookies.php
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2019-07-17 Chrome Development Tool: [VM] file from javascript
2019-07-17 Forcepoint
2019-07-17 ASP.NET Web Optimization Framework
2017-07-17 常用快捷键
2017-07-17 Track Active Item in Solution Explorer
2015-07-17 Learning WCF Chapter2 Service Contracts
2015-07-17 Learning WCF Chapter2 WCF Contracts and Serialization