Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cookie path and its accessibility to subfolder pages

Let say I have a website with domain: www.example.com

If I set a cookie with path '/' the cookie will be accessible via all pages in the domain, eg:

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

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

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

So, if not, I guess, I have no choice but to use path '/' for those cookies, right?

like image 528
Nordin Avatar asked Feb 23 '09 04:02

Nordin


People also ask

What is a cookie path?

Cookie PathThe Path directive of a cookie determines the URL path for which the cookie will be valid. For example, if a cookie has been declared to include the directive “path=/“, the cookie will be valid for all application paths, from the root directory downwards on the web server.

Are cookies shared between pages?

Cookie is shared by default if you correctly specify the domain and the path.

Can you set cookie on a different path?

is it possible to access cookies set on a different path (but same domain) with js? Yes it is possible by using the path attribute.

How do I find my cookie path?

The getPath() method of HttpCookie class is used to return the path on the server for which the browser return the cookie. The cookie will be visible to all the sub paths on the given server.


2 Answers

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.

like image 131
Alex Barrett Avatar answered Oct 04 '22 07:10

Alex Barrett


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.

like image 43
Michael Avatar answered Oct 04 '22 05:10

Michael