HTTP请求中是否允许多个Cookie头?

118

通常,浏览器将 cookie 组合成一个单独的 Cookie 标头,例如:

Cookie: a=1; b=2

标准是否允许将它们作为单独的标头发送,例如:

Cookie: a=1
Cookie: b=2

它们是否总是必须在同一行上?

2个回答

158

在查找有关此主题的详细信息时,偶然发现了此页面。来自HTTP状态管理机制RFC 6265的一条引用应该会使事情更清晰:

5.4. Cookie标头

当用户代理生成HTTP请求时,用户代理不能附加多个Cookie标头字段。

看起来实际上是禁止使用多个Cookie标头!


9
这些新奇古怪的RFC文件。 :) - Kylar
19
请注意,服务器 可以响应多个 Set-Cookie 头部:http://tools.ietf.org/html/rfc6265#page-7 - Michael Haren
2
为什么要踩,因为OP明确要求在HTTP请求方面,而不是HTTP响应方面。@JeffDavenport - James Chong
2
对于像Jeff这样从Google过来的人,OP表明您可以通过使用“;”分隔它们(不需要空格)来拥有多个变量。 - Albert Hendriks
2
@HawkeyeParker - “can”并不意味着“正确”。如果这些值是由单个服务器设置的,我会认为Set-Cookie:a=b;c=d;Set-Cookie:a=b; Set-Cookie:c=d;更正确。规范指出,服务器不应将多个Set-Cookie头字段折叠成一个字段,但可以将多个Set-Cookie头字段添加到一个响应中。在现实世界中,这意味着当代理服务器传递响应时,如果该代理设置cookie,则应使用单独的Set-Cookie头。 - Golphy
显示剩余6条评论

47

现在HTTP/2 (RFC 7540)中已经允许,规定如下:

    8.1.2.5.  Compressing the Cookie Header Field

   The Cookie header field [COOKIE] uses a semi-colon (";") to delimit
   cookie-pairs (or "crumbs").  This header field doesn't follow the
   list construction rules in HTTP (see [RFC7230], Section 3.2.2), which
   prevents cookie-pairs from being separated into different name-value
   pairs.  This can significantly reduce compression efficiency as
   individual cookie-pairs are updated.

   To allow for better compression efficiency, the Cookie header field
   MAY be split into separate header fields, each with one or more
   cookie-pairs.  If there are multiple Cookie header fields after
   decompression, these MUST be concatenated into a single octet string
   using the two-octet delimiter of 0x3B, 0x20 (the ASCII string "; ")
   before being passed into a non-HTTP/2 context, such as an HTTP/1.1
   connection, or a generic HTTP server application.

   Therefore, the following two lists of Cookie header fields are
   semantically equivalent.

     cookie: a=b; c=d; e=f

     cookie: a=b
     cookie: c=d
     cookie: e=f

“如果在解压缩后存在多个Cookie头字段,则必须将它们连接成单个八位字节字符串”,这样做的原因是什么?兼容性?当处理“通用HTTP服务器应用程序”时,肯定没有实际优势。 - ioquatix
如果您查看已接受的答案,您会发现这是因为旧规范(HTTP/2之前)禁止多个“Cookie”标头。因此,在传递给旧服务器时,您必须将它们连接起来,否则将违反规范,并可能导致不可预测的行为(例如,HTTP/1.1代理服务器可能会删除额外的重复标头)。 - Malvineous

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接