在 HEAD 响应中避免 Content-Length

Avoiding Content-Length in HEAD response

Content-Length 响应 header 为 just HEAD 请求生成通常很昂贵(例如,在处理动态生成的资源时),但在完成工作后可能本质上 "free"需要生成 GET 响应 body.

当响应 GET 请求时提供 Content-Length(而不是分块响应)是合理的,但计算相应 HEAD 请求的 Content-Length 不合理或缓慢时,是允许 HEAD 响应:

relevant W3C specification表示HEAD请求"SHOULD"(不是"MUST")以相同的header响应;在 GET 响应中使用 Content-Length 的清洁度和总传输大小节省(通常是次要的)值得在 HEAD 的情况下违反上述 "SHOULD" ,或者是让两个响应都发送的唯一合理选择一个 Transfer-Encoding: chunked header?

感谢@julian-reschke 的提示,rfc-7231 表明:

The server SHOULD send the same header fields in response to a HEAD request as it would have sent if the request had been a GET, except that the payload header fields (Section 3.3) MAY be omitted.

对于同一文档的 section 3.3,有效负载 header 字段包括:

  • Content-Length
  • Content-Range
  • 预告片
  • Transfer-Encoding