[nginx]定制http头信息

前言

修改http响应头信息,相关Nginx模块:ngx_http_headers_module

expires

  • 语法:
    • expires [modified] time;
    • expires [modified] time;
  • 默认值:expires off;
  • 作用域:http, server, location, if in location
  • 用途:控制缓存时间
  • 示例:
# 不缓存
expires -1;
# 缓存一小时
expires 1h;

# 根据变量设置缓存时间
## 默认禁止缓存
## 如果Content-Type 是 application/pdf,则缓存42天
## 如果 Content-Type 是 image/ ,则缓存7天
map $sent_http_content_type $expires {
    default         off;
    application/pdf 42d;
    ~image/         7d;
}

expires $expires;
  • 注意事项:
    • 只有正常响应时才会被缓存
    • 如果业务系统缺少Last-Modified响应头,大部分浏览器并不会缓存

add_header

  • 语法:add_header name value [always];
  • 默认值:无
  • 作用域:http, server, location, if in location
  • 用途:添加自定义的响应头
  • 示例:
add_header Access-Control-Allow-Methods 'GET, POST, PUT';
  • 注意事项:
    • 只有正常响应时才会返回自定义的响应头,像404、500这类异常状态码需要指定always参数才能返回自定义响应头。
    • 后端业务系统如果返回同名响应头,可能会引起bug。

参考

posted @ 2022-07-27 10:33  花酒锄作田  阅读(244)  评论(0编辑  收藏  举报