更新履歴

  1. : デジタルサーカス株式会社の社内記事として公開
  2. : ブログ記事として一般公開
NOTE
この記事は、2022-08-18 にデジタルサーカス株式会社 の社内 Qiita Team に公開された記事をベースに、加筆修正して一般公開したものです。

はじめに

HTTP version 1.1 で同じ名前のヘッダを2回送ると、どのように解釈されるのか。仕様を確認した。

今回読んだ仕様は RFC 7230 で、こちらのリンクから閲覧できる: https://datatracker.ietf.org/doc/html/rfc7230

その中でも、https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.2 を主に引用する。

ところで、HTTP 周りの仕様を探すときはここから飛ぶと便利: https://developer.mozilla.org/en-US/docs/Web/HTTP/Resources_and_specifications

仕様

送信側

A sender MUST NOT generate multiple header fields with the same field name in a message unless either the entire field value for that header field is defined as a comma-separated list [i.e., #(values)] or the header field is a well-known exception (as noted below).

【日本語訳 (私が訳したもので、公式なものではない)】 送信者は、同じ field name の header field を複数生成してはならない (MUST NOT)。ただし、header field の値がコンマ区切りのリストとして定義されているか、header field がよく知られた例外 (後述) である場合はその限りでない。

受信側

A recipient MAY combine multiple header fields with the same field name into one "field-name: field-value" pair, without changing the semantics of the message, by appending each subsequent field value to the combined field value in order, separated by a comma. The order in which header fields with the same field name are received is therefore significant to the interpretation of the combined field value; a proxy MUST NOT change the order of these field values when forwarding a message.

【日本語訳 (私が訳したもので、公式なものではない)】 受信者は、同じ field name を持つ複数の header field を、メッセージの意味を変えないようにしつつ同じ順序で追加して、単一のコンマで区切られた "field-name: field-value" のペアに結合してよい (MAY)。したがって、同じ field name を持つ header field がどのような順序で受信されたかは、結合された値の解釈に影響する。よって、プロキシは、メッセージを転送する際、header field の順序を変えてはならない (MUST NOT)。

例外ケース: Set-Cookie

Note: In practice, the "Set-Cookie" header field ([RFC6265]) often appears multiple times in a response message and does not use the list syntax, violating the above requirements on multiple header fields with the same name. Since it cannot be combined into a single field-value, recipients ought to handle "Set-Cookie" as a special case while processing header fields. (See Appendix A.2.3 of [Kri2001] for details.)

【日本語訳 (私が訳したもので、公式なものではない)】 注意: 実際には、Set-Cookie header field (RFC6265) は、しばしばレスポンスメッセージ中に複数回現れる。これはリストの構文を使っておらず、上述した同じ field name を持つ header field についての要件に違反している。この値は単一の値へ結合できないため、受信者は、header field を処理する際、Set-Cookie を特別扱いした方がよい。

おそらく、「送信側」のところで書かれている「よく知られた例外」の一つがこれだと思われる。

どの header field がコンマ区切りのリストなのか

上記のように、同じ field name を持つ header field を複数回送れるかどうかは、その header field がコンマ区切りのリストとして定義されているかどうかで決まる。では、特定の header field がその条件を満たしているかどうか知りたいときは、何を見ればよいのか。

HTTP の仕様として定義されているような header field であれば、下記のリンクからそれぞれの定義を参照できる。

そうでない場合 (たとえば X- から始まるもの等) は、MDN や各ベンダのドキュメントを探すことになるだろう。

まとめ

  • 送信側: 基本的には複数回送れない。コンマ区切りのヘッダは例外
  • 受信側: 基本的には未規定。コンマ区切りのヘッダは複数回来たらその順に結合する
  • プロキシ: 順序を変えてはならない
  • Set-Cookie は例外ケース