每个网络请求都会发送浏览器的cookie吗?

我说的不是页面浏览量,而是对图像、.js文件等的请求。

更新 如果一个网页有50个元素,那就是50个请求。为什么它会为每个请求发送相同的cookie(s),它不是缓存或知道它已经有了它吗?


当前回答

不。并不是每个请求都发送cookie。这取决于cookie配置和客户-服务器连接。

例如,如果cookie的安全选项设置为true,那么它必须通过安全HTTPS连接传输。意味着当你看到该网站与HTTP协议,然后这些cookie不会被浏览器发送,因为安全标志是真的。

其他回答

简短的回答是肯定的。下面的代码行来自JS文档

cookie曾经被用于一般的客户端存储。虽然当它们是在客户端上存储数据的唯一方式时,这是合法的,但现在建议使用现代存储api。cookie随每个请求一起发送,因此它们会降低性能(特别是对于移动数据连接)。

是的,只要请求的URL在cookie中定义的相同域和路径(以及所有其他限制——安全、httponly、未过期等)保持,那么cookie将为每个请求发送。

是的。每个请求都发送属于同一个域的cookie。它们不是缓存的,因为HTTP是无状态的,这意味着每个请求都必须足够让服务器知道如何处理它。假设你的图片只能被特定的用户访问;你必须在这50个请求中每一个都发送你的身份验证cookie,这样服务器就知道它收到的请求池中是你而不是其他人或客人。

Having said that, cookies might not be sent given other restrictions mentioned in the other responses, such as HTTPS setting, path or domain. Especially there, an important thing to notice: cookies are not shared between domains. That helps with reducing the size of HTTP calls for static files, such as the images and scripts you mentioned. Example: you have 4 cookies at www.stackoverflow.com; if you make a request to www.stackoverflow.com/images/logo.png, all those 4 cookies will be sent. However, if you request stackoverflow.com/images/logo.png (notice the subdomain change) or images.stackoverflow.com/logo.png, those 4 cookies won't be present - but maybe those related to these domains will.

您可以阅读更多关于cookie和图像请求,例如,在这篇StackOverflow博客文章。

不。并不是每个请求都发送cookie。这取决于cookie配置和客户-服务器连接。

例如,如果cookie的安全选项设置为true,那么它必须通过安全HTTPS连接传输。意味着当你看到该网站与HTTP协议,然后这些cookie不会被浏览器发送,因为安全标志是真的。

I know this is an old thread. But I've just noticed that most browsers won't sent cookies for a domain if you add a trailing dot. For example http://example.com. won't receive cookies set for .example.com. Apache on the other hand treats them as the same host. I find this useful to make cross domain tracking more difficult for external resources I include, but you could also use it for performance reasons. Note this brakes validation of https certificates. I've run a few tests using browsershots and my own devices. The hack works on almost all browsers except for safari (mobile and desktop), which will include cookies in the request.