layout: posttitle: Nginx 操作响应头信息
subtitle: Nginx 操作响应头信息
date: 2019-05-28
author: he xiaodong
header-img: img/default-post-bg.jpg
catalog: true
tags:
- Nginx
- 响应头信息
- add_header
- add_trailer

前置条件:需要编译 ngx_http_headers_module 模块,才支持 header 头信息操作

add_header

意思为将自定义的头信息的添加到响应头,指令为 add_header name value [always];,可以用在 http {}, server {}, location {}, if in location {} 上下文中,
只有当响应状态码等于 200, 201 (1.3.10), 204, 206, 301, 302, 303, 304, 307 (1.1.16, 1.0.13), 或 308 (1.13.0) 时生效,如果 always 参数指定了,头信息将无视状态码,在所有响应中强制返回。

注意: 可以声明多个 addheader 指令,当且仅当_ 当前区块没有 add_header 的时候,才会继承上级声明的 add_header 信息

例如:

  1. server {
  2. add_header a 123;
  3. location / {
  4. root /path;
  5. }
  6. location /download/ {
  7. add_header b 321;
  8. }
  9. }

如上的例子,在访问 /download/ 路由的时候,将返回 b 321 这样的头信息,而访问 / 路由时,将返回上级指定的 a 123 头信息。

add_trailer

意思为将自定义的头信息添加到响应头的末尾,指令为 add_trailer name value [always];,可以用在 http {}, server {}, location {}, if in location {} 上下文中,只有当响应状态码等于 200, 201, 206, 301, 302, 303, 307, 或 308 时生效,如果 always 参数指定了,头信息将无视状态码,在所有响应中强制返回。

注意: 可以声明多个 addtrailer 指令,当且仅当_ 当前区块没有 add_trailer 的时候,才会继承上级声明的 add_trailer 信息

举例参考 add_header 的例子。

expires

启用或禁用,添加或修改响应头中的 “Expires” 和 “Cache-Control” 字段,指令为 expires [modified] time; 或者 expires epoch | max | off; 当响应状态码等于200, 201 (1.3.10), 204, 206, 301, 302, 303, 304, 307 (1.1.16, 1.0.13), 或 308 (1.13.0) 时生效,time 参数可以为正时间或者负时间。”Expires” 字段中的时间计算为当前时间和在 time 中指定的时间总和。如果使用该 modified 参数(0.7.0,0.6.32),则将时间计算为文件修改时间与 time 指令中指定的时间之和。

此外,可以使用 “@” 前缀(0.7.9,0.6.34)指定一天中的时间:expires @15h30m;

“Cache-Control” 字段的内容取决于指定时间的符号:

  • 时间为负数 - “Cache-Control: no-cache”
  • 时间为正数或者0 - “Cache-Control: max-age=t” t 是指令中指定的时间,以秒为单位

epoch 参数将 “Expires” 设置为值 “Thu, 01 Jan 1970 00:00:01 GMT”,将”Cache-Control” 设置为 “no-cache”。

max 参数将 “Expires” 设置为值 “Thu, 31 Dec 2037 23:55:55 GMT”,将”Cache-Control” 设置为 10 年。

off 参数禁用添加或修改 “Expires” 和 “Cache-Control” 响应头字段。

最后一个参数值可以包含变量(1.7.9): 例如:

  1. map $sent_http_content_type $expires {
  2. default off;
  3. application/pdf 42d;
  4. ~image/ max;
  5. }
  6. expires $expires;

© 主体内容翻译自 Module ngx_http_headers_module docs, 做了一些调整和示例

最后恰饭 阿里云全系列产品/短信包特惠购买 中小企业上云最佳选择 阿里云内部优惠券