温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Nginx 操作响应头信息的实现

发布时间:2020-09-07 23:01:06 来源:脚本之家 阅读:177 作者:he_xd 栏目:服务器

前置条件:需要编译 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 参数指定了,头信息将无视状态码,在所有响应中强制返回。

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

例如:

server {
 add_header a 123;

 location / {
  root /path;
 }

 location /download/ {
  add_header b 321;
 }
}

如上的例子,在访问 /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 参数指定了,头信息将无视状态码,在所有响应中强制返回。

注意: 可以声明多个 add_trailer 指令,当且仅当 当前区块没有 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 @15h40m;

"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): 例如:

map $sent_http_content_type $expires {
 default   off;
 application/pdf 42d;
 ~image/   max;
}

expires $expires;

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI