在子域和域之间共享 cookie [英] Share cookie between subdomain and domain
问题描述
我有两个问题.我明白,如果我在 cookie 中将域指定为 .mydomain.com
(带前导点),则所有子域都可以共享一个 cookie.
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.
subdomain.mydomain.com
能否访问在 mydomain.com
中创建的 cookie(没有 www
子域)?
Can subdomain.mydomain.com
access a cookie created in mydomain.com
(without the www
subdomain)?
如果在 subdomain.mydomain.com
中创建,mydomain.com
(没有 www
子域)可以访问 cookie 吗?
Can mydomain.com
(without the www
subdomain) access the cookie if created in subdomain.mydomain.com
?
推荐答案
两个不同的域(例如 mydomain.com
和 subdomain.mydomain.com
,或 sub1.mydomain.com
和 sub2.mydomain.com
) 只能共享 cookie,如果域在 Set-Cookie
标头中明确命名.否则,cookie 的范围仅限于请求主机.(这被称为仅限主机的 cookie".参见 什么是主机只有饼干?)
Two different domains (e.g. mydomain.com
and subdomain.mydomain.com
, or sub1.mydomain.com
and sub2.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?)
例如,如果您从 subdomain.mydomain.com
发送以下标头,则 cookie 将仅针对对该域的请求发送,而不会针对对任何其他域的请求发送域:
For instance, if you sent the following header from subdomain.mydomain.com
, then the cookie would only be sent for requests to that domain, and won't be sent for requests to any other domains:
Set-Cookie: name=value
但是,如果您使用以下内容,它将在两个域中都可用:
However if you use the following, it will be usable on both domains:
Set-Cookie: name=value; domain=mydomain.com
此 cookie 将发送给 mydomain.com 的任何子域,包括嵌套子域,例如 subsub.subdomain.mydomain.com
.
This cookie will be sent for any subdomain of mydomain.com, including nested subdomains like subsub.subdomain.mydomain.com
.
在 RFC 2109 中,没有前导点的域意味着它不能在子域上使用,只有一个前导点 (.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).
但是,所有现代浏览器都遵守较新的规范 RFC 6265,并且会忽略任何前导点,表示您可以在子域和顶级域上使用 cookie.
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.
总而言之,如果您从 mydomain.com
设置一个 cookie,就像上面的第二个示例一样,它可以被 subdomain.mydomain.com
访问,反之亦然.这也可用于允许 sub1.mydomain.com
和 sub2.mydomain.com
共享 cookie.
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.
另见:
这篇关于在子域和域之间共享 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!