服务器如何设置 HTTP 响应 headers?

How do servers set HTTP response headers?

我觉得我会因为问这么简单的问题而感到尴尬,但我已经研究了好几天了,找不到任何有用的信息。

什么决定服务器发送的 HTTP 响应 header?如果我控制服务器(如果我们需要具体性,比如说 Apache),那么我可以编辑什么文件来更改响应 header?例如,将其设置为包含 Content-Length 而不是 Transfer-Encoding: chunked?

我知道 PHP 和 Java Servlet 可用于操作 header。不过,响应 headers 的存在和内容是 HTTP 的基础,因此应该存在一种无需使用外部技术即可对其进行编辑的方法,不是吗?

某些 header 是自动设置的。它们是 HTTP 规范的一部分,服务器会为您处理它们。这就是 Web 服务器的用途,以及它不同于 FTP 服务器或文件共享的原因。例如 Content-Length 很容易被网络服务器计算出来,需要设置,所以服务器会自动执行。

某些其他 header 是根据配置设置的。 Apache 通常会加载一个主配置文件(通常称为 httpd.conf 或 apache2.conf),但是随后,为了避免这个文件陷入一个大而笨拙的混乱中,它通常会从中加载其他文件。这些文件只是带有配置文本行的文本文件,用于更改服务器的行为。其他网络服务器可能使用 XML 配置文件,并且可能有一个 GUI 来控制配置(例如 IIS)

因此,对于某些 header,您可能没有显式设置 header 值,但您基本上配置了服务器,然后它使用该配置找出合适的 headers 发送。例如,您可以将服务器配置为 gzip 某些文件(例如,文本文件而不是已经压缩的 jpg)。在 Apache 中,这是由 mod_deflate module and the config options it gives you. Once the appropriate config is added to the server config, the server will do the necessarily processing (e.g. gzip the file or not depending on type) and then automatically add the headers. So an Apache module is basically something that changes how the server works and this may or may not the also set headers. Another example is for sending caching headers to tell the browser how long to cache files for. This is controlled by adding the mod_expiries module 及其允许的所有配置选项处理的。虽然其中一些 header 可以被硬编码(例如 Cache-Control),但其他一些依赖于 Apache 进行计算(例如 Expires),因此最好使用该模块根据您的配置为您执行此操作。

最后,您可以在服务器中显式设置 headers(在 Apache 中,这是使用 mod_headers 模块完成的)。这对于添加到浏览器的新功能很有用(例如 HSTS、CSP 或 HPKP),其中服务器不需要做任何事情,只需添加 header 并且客户端(例如网络浏览器)知道要做什么和他们一起做。例如,您可以通过将此配置添加到 httpd.conf:

来添加 JonahHuron header
Header always set JonahHuron "Some Value"

至于是否使用header完全取决于接收响应的程序。