Nginx 操作响应头信息

栏目: 服务器 · Nginx · 发布时间: 6年前

内容简介:前置条件:需要编译意思为将自定义的头信息的添加到响应头,指令为注意: 可以声明多个 add_header 指令,

前置条件:需要编译 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 @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): 例如:

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

expires $expires;

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


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Math Adventures with Python

Math Adventures with Python

Peter Farrell / No Starch Press / 2018-11-13 / GBP 24.99

Learn math by getting creative with code! Use the Python programming language to transform learning high school-level math topics like algebra, geometry, trigonometry, and calculus! In Math Adventu......一起来看看 《Math Adventures with Python》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具