为什么,如果我创建www.example.com一个cookie,并检查它在example.com,则cookie不存在呢?我计划只使用的.htaccess
重定向非www到WWW域。但是,我怎么解决这个问题?
Why is it that if I create a cookie on www.example.com and check it on example.com, the cookie doesn't exist there? I am planning to just use .htaccess
redirect non-www to a www domain. But how do I solve this?
浏览器是这里的主要元凶,而不是PHP。它们存储由域,不知道 WWW
是一个特例;从他们的角度来看, www.mydomain.com
和 mydomain.com
是不同的字符串,因此具有不同的安全策略。然而,也有一些是你可以做的。
Browsers are the main culprit here, not PHP. They store by domain, and don't know that www
is a special case; from their perspective, www.mydomain.com
and mydomain.com
are different strings, and therefore have different security policies. However, there is something you can do.
在设置cookie,使用 .mydomain.com
(与前面的点)。这会告诉你的用户的浏览器进行的cookie访问 mydomain.com
和所有子域名,包括 WWW
。 PHP的的setcookie 有说法 $域
,但它排在第五位,所以你可能需要设置 $过期
和 $ PATH
来,为了得到它的默认值。
When setting the cookie, use .mydomain.com
(with the leading dot). This will tell your user's browser make the cookie accessible to mydomain.com
and all subdomains, including www
. PHP's setcookie has the argument $domain
, but it's fifth on the list, so you may need to set $expire
and $path
to their default values in order to get at it.
setcookie('name', 'value', time()+3600, '/', '.mydomain.com');
有关的一致性,但是,您不妨考虑重新路由所有网络流量到一个特定的领域,即发 mydomain.com
流量 WWW。 mydomain.com
,反之亦然。我模糊的SEO知识(编辑如果不正确)告诉我,这是有益的,以免有重复的内容,这样可以节省大家这样的认证问题。此外,如果您存储资产的子域,有饼干在那里不必每次运送,所以存储应用程序的Cookie只在 WWW
减慢流量赚取你的速度提升
For consistency, however, you may wish to consider rerouting all web traffic to a specific domain, i.e. send mydomain.com
traffic to www.mydomain.com
, or vice-versa. My vague knowledge of SEO (edit if incorrect) tells me that it's helpful so as not to have duplicate content, and it saves you all such authentication issues. Additionally, if you store assets on a subdomain, having cookies on there slows down traffic by having to transport it each time, so storing application cookies only on www
earns you that speed boost.
这里是如何完成这样的重定向Apache中的教程。