Cookie 路径及其对子文件夹页的可访问性

假设我有一个域名为 www.example.com 的网站

如果我设置一个 Cookie 的路径为“ < em >/ ”,Cookie 将可以通过域中的所有页面访问,例如:

  • Www.example.com/page1.html
  • Www.example.com/subfolder1/page1.html
  • Www.example.com/subfolder1/moresubfolder1/page1.html 等。

如果我们将 Cookie 设置为路径“ < em >/subfolder1 ”,Cookie 是否会对文件夹下的任何页面或子文件夹可用?例如:

  • Www.example.com/subfolder1/moresubfolder/page1.html

所以,如果没有,我想,我别无选择,只能使用路径’/’为这些饼干,对不对?

95941 次浏览

If we set the cookie to path '/subfolder1', will the cookie will be made available to any page or subfolder beneath the folder?

Yes. The cookie will be available to all pages and subdirectories within the /subfolder1 path.

if we set the cookie to path /subfolder1, the following pages in the example are accessible:

www.example.com/subfolder1/page1.html
www.example.com/subfolder1/moresubfolder1/page1.html
etc.

However, the page www.example.com/page1.html will not be accessible as it does not belong to the allowed path.

To remove some ambiguity by reusing a portion of this answer:

A request-path path-matches a given cookie-path if at least one of the following conditions holds:

  • The cookie-path and the request-path are identical.
  • The cookie-path is a prefix of the request-path, and the last character of the cookie-path is %x2F ("/").
  • The cookie-path is a prefix of the request-path, and the first character of the request-path that is not included in the cookie-
    path is a %x2F ("/") character.

There is a slight (but potentially important) difference between setting a cookie on the /subfolder1 path and the /subfolder1/ path.

If you rely on the former your request path needs to start with a "%x2F ("/") character" (a forward slash) to guarantee the desired behaviour. For an example, take a look at the linked answer.

Setting the cookie path to simply / avoids any edge cases, but as you say - the cookie would be accessible the entire domain.