缓存

本文档介绍了如何通过启用页面规则中的缓存选项对静态资源或较少变动的内容进行缓存操作。 利用缓存可显著提升资源的访问速度并优化最终用户的体验。

参数说明

参数名数据类型是否必选参数描述
cache_keyarray用于标识缓存资源的键值
enforce_cachebool是否忽略服务器响应头中的 Cache-Control 或 Expires 等缓存指令,而采用 default_ttls 参数定义的默认缓存策略
default_ttlsarray默认的缓存失效时间策略
browser_ttlarray设置浏览器端的缓存有效期
browser_ttl_unitarray浏览器缓存有效期的单位,可选值有 s(秒)、min(分钟)、hour(小时)、day(天)
disable_convert_headbool是否将 HEAD 请求转换为 GET 请求,缺省值为 true

参数 cache_key 是用于生成标识缓存的 key 的数组。

不带参数的 cache key 有以下常见选择:

  • uri:请求的 URI,例如 /hello.html。
  • sorted-query-string:经过排序的查询参数。
  • query-string:查询参数。
  • user-agent:用户代理。
  • scheme:协议类型,可能是 http 或 https。
  • client-continent: 客户所在的大洲,默认通过客户端 IP 地址来识别,也可以通过 X-Forwarded-For 请求头的第一个地址来识别。
  • req-method:HTTP 请求方法,如 CONNECT、DELETE、GET、HEAD、POST、PUT、TRACE、OPTIONS、PATCH 等。
  • first-x-forwarded-addr:X-Forwarded-For 请求头中的第一个 IP 地址,如 1.1.1.1,2.2.2.2 中的 1.1.1.1
  • last-x-forwarded-addr:X-Forwarded-For 请求头中的最后一个 IP 地址,如 1.1.1.1,2.2.2.2 中的 2.2.2.2
  • http-version:HTTP 版本号,可能是 2.0、1.1、1.0、0.9。

带参数的 cache key 有以下常见选择:

  • uri-arg:URI 中的参数,例如 hello.html?username=openresty 中的 username
  • req-header:请求头信息,例如 Host: openresty.com 中的 Host
  • req-cookie:请求中的 Cookie,例如 Cookie: token=tokenvalue 中的 token

参数 browser_ttlbrowser_ttl_unit 用于定义浏览器端的缓存设定,在设定的缓存期限内,浏览器将从本地缓存读取资源。

default_ttls 参数是一个数组格式,允许设置多个缓存策略。策略中的具体参数包括:

参数名数据类型是否必选参数描述
ttlnumber定义缓存的生命周期
ttl_unitstring缓存生命周期的单位,支持 s(秒)、min(分钟)、hour(小时)、day(天)
statusnumber指定响应状态码下的缓存策略

配置示例

- enable_rule: true
  conditions:
  - op: prefix
    var: uri
    val: /static/

  cache:
    cache_key:
      - name: uri
      - name: query-string
      - name: req-header
        args: Host
      - name: uri-arg
        args: argname
      - name: req-cookie
        args: cookiename
      - name: client-continent  # means args: client-addr
      - name: client-continent
        args: first-x-forwarded-addr
    enforce_cache: true
    default_ttls:
      - ttl_unit: min
        status: 200
        ttl: 300
    browser_ttl: 300
    browser_ttl_unit: min
    disable_convert_head: false

在该示例中,检查请求的 URI 是否以 /static/ 作为前缀。如果是,将启动缓存机制,其中缓存键由 URI 和请求参数组成,缓存时间设置为 300 分钟。