5.2 Caching Hash Keys 配置缓存哈希键名

Problem

You need to control how your content is cached and looked up.

问题

自定义如何缓存和查找缓存内容


Solution

Use the proxy_cache_key directive, along with variables to define

what constitutes a cache hit or miss:

proxy_cache_key "$host$request_uri $cookie_user";

This cache hash key will instruct NGINX to cache pages based on

the host and URI being requested, as well as a cookie that defines

the user. With this you can cache dynamic pages without serving

content that was generated for a different user.

解决方案

通过一条单独的 proxy_cache_key 指令,以变量名的形式定义缓存命中和

丢弃的规则。

proxy_cache_key "$host$request_uri $cookie_user";

上例指令依据请求域名、请求 URI 和用户 cookie 作为缓存

键名,来构建 NGINX 的缓存页面。这样,就可以对动态页面进行缓存,而

无需对每个用户都进行缓存内容的生成处理。


Discussion

The default proxy_cache_key is "$scheme$proxy_host

$request_uri". This default will fit most use cases. The variables

used include the scheme, HTTP or HTTPS, the proxy_host, where

the request is being sent, and the request URI. All together, this

reflects the URL that NGINX is proxying the request to. You may

find that there are many other factors that define a unique request

per application, such as request arguments, headers, session identifi‐

ers, and so on, to which you’ll want to create your own hash key

Selecting a good hash key is very important and should be thought

through with understanding of the application. Selecting a cache key

for static content is typically pretty straightforward; using the host‐

name and URI will suffice. Selecting a cache key for fairly dynamic

content like pages for a dashboard application requires more knowl‐

edge around how users interact with the application and the degree

of variance between user experiences. For security concerns you

may not want to present cached data from one user to another

without fully understanding the context. The proxy_cache_key

directive configures the string to be hashed for the cache key. The

proxy_cache_key can be set in the context of HTTP, server, and

location blocks, providing flexible control on how requests are

cached.

结论

proxy_cache_key 默认设置是 "$scheme$proxy_host $request_uri"。默认设置

适用于多数的使用场景。配置之中包括 scheme、HTTP 或 HTTPS、代理域名

(proxy_host)、请求的 URI 等变量。总之,它们能够正确处理 NGINX 代理请求。

您可能会发现,对于每个应用程序,有许多其他的因素可以定义一个惟一的请求,

比如请求参数、头文件、会话标识符等等,您需要创建自己的散列键。或许你

已经发现,对一个应用,还有其它的数据能够确定一个唯一的请求,比如请求参数、

请求头(headers)、会话标识(session identifiers) 等等,这些都可以用于

构建自己的散列键名。在构建时应基于应用程序的理解,创建选择一个好的散列

键名,这一点非常重要。比较简单的是为静态内容创建缓存键名,通常,可以直接

使用域名(hostname)和请求 URI 就可以了。而类似于仪表盘这类的,具有动态内

容的页面,则需要充分了解用户和应用之间的交互、以及用户体验之间的差异,来

构建缓存键名。如从安全的角度触发,你可能不希望缓存将一个用户的缓存数据展

示给另外的用户。proxy_cache_key 令配置了用于缓存生成哈希值字符,此条指令

可以在 HTTP、server、location 块级指令上下文中定义,实现对请求如何缓存的

灵活控制。

results matching ""

    No results matching ""