Nginx Proxy Cache配置详解

Nginx作为高性能的HTTP和反向代理服务器,被广泛用于Web应用的负载均衡和静态内容服务。其中,Nginx的Proxy Cache功能允许我们将代理请求的结果缓存起来,以减少对后端服务器的请求次数,提高网站的响应速度。

一、Proxy Cache 工作原理

当客户端发起请求时,Nginx首先会检查缓存中是否有该请求的结果。如果有,Nginx会直接从缓存中返回结果,不再向后端服务器发起请求。如果缓存中没有,Nginx会向后端服务器发起请求,并将返回的结果存入缓存,然后再返回给客户端。

二、Proxy Cache 配置参数详解

名称 默认配置 作用域 官方说明 中文解读 模块
proxy_cache proxy_cache off; http, server, location Defines a shared memory zone used for caching. The same zone can be used in several places. Parameter value can contain variables (1.7.9). The off parameter disables caching inherited from the previous configuration level. 设置是否开启对后端响应的缓存,如果开启的话,参数值就是zone的名称,比如proxy_cache mycache ngx_http_proxy_module
proxy_cache_valid 没有默认值,实例如proxy_cache_valid 200 302 10m; http, server, location Sets caching time for different response codes. 针对不同的response code设定不同的缓存时间,如果不设置code,默认为200,301,302,也可以用any指定所有code ngx_http_proxy_module
proxy_cache_key proxy_cache_key $scheme$proxy_host$request_uri; http, server, location Defines a key for caching 给缓存设定key,默认值相当于proxy_cache_key $scheme$proxy_host$uri$is_args$args; ngx_http_proxy_module
proxy_cache_path 没有默认值,实例proxy_cache_path /var/cache levels=1:2 keys_zone=imgcache:100m inactive=2h max_size=1g; http Sets the path and other parameters of a cache. Cache data are stored in files. The file name in a cache is a result of applying the MD5 function to the cache key. The levels parameter defines hierarchy levels of a cache: from 1 to 3, each level accepts values 1 or 2. 指定缓存存储的路径,文件名为cache key的md5值,然后多级目录的话,根据level参数来生成,比如levels=1:2:3,第一个目录名取md5值的倒数第一个值,第二个目录名取md5值的第2和3个值,第三个目录名取md5值的第4,5,6个值;key_zone参数用来指定在共享内存中缓存的元数据的名称和内存大小,比如keys_zone=imgcache:100m,所有的缓存查找首先经过这里查找元数据,如果命中再去文件系统查找相应的缓存 ;inactive用来指定缓存没有被访问超时移除的时间,默认是10分钟,也可以自己指定比如inactive=2h ;max_size 用来指定缓存的最大值,超过这个值则会自动移除最近最少使用的缓存 ngx_http_proxy_module
proxy_cache_bypass 没有默认值 http, server, location Defines conditions under which the response will not be taken from a cache. If at least one value of the string parameters is not empty and is not equal to “0” then the response will not be taken from the cache. 指定哪些响应在某些值不为空或不为0的情况下不走缓存,比如proxy_cache_bypass $http_pragma $http_authorization; ngx_http_proxy_module
proxy_cache_min_uses proxy_cache_min_uses 1; http, server, location Sets the number of requests after which the response will be cached. 指定在多少次请求之后才缓存响应内容 ngx_http_proxy_module
proxy_cache_use_stale proxy_cache_use_stale off; http, server, location Determines in which cases a stale cached response can be used during communication with the proxied server. The directive’s parameters match the parameters of the proxy_next_upstream directive. 指定在后端服务器在返回什么状态码的情况下可以使用过期的缓存,比如proxy_cache_use_stale error timeout invalid_header http_500 http_502 http_503 http_504; ngx_http_proxy_module
proxy_cache_lock proxy_cache_lock off; http, server, location When enabled, only one request at a time will be allowed to populate a new cache element identified according to the proxy_cache_key directive by passing a request to a proxied server. Other requests of the same cache element will either wait for a response to appear in the cache or the cache lock for this element to be released, up to the time set by the proxy_cache_lock_timeout directive. 默认不开启,开启的话则每次只能有一个请求更新相同的缓存,其他请求要么等待缓存有数据要么限时等待锁释放;nginx 1.1.12才开始有 ngx_http_proxy_module
proxy_cache_lock_timeout proxy_cache_lock_timeout 5s; http, server, location Sets a timeout for proxy_cache_lock. When the time expires, the request will be passed to the proxied server, however, the response will not be cached. 等待缓存锁超时之后将直接请求后端,结果不会被缓存 ; nginx 1.1.12才开始有 ngx_http_proxy_module

关键配置

  • proxy_cache_path:定义缓存文件的存储路径和缓存目录结构。
    • proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
  • proxy_cache:开启或关闭代理缓存功能,并指定缓存区域。
  • proxy_cache my_cache;
  • proxy_cache_valid:定义不同HTTP响应码的缓存有效期。
    • proxy_cache_valid 200 304 12h;
    • proxy_cache_valid 301 302 1h;
  • proxy_cache_key:定义缓存的键,用于区分不同的缓存项。
    • proxy_cache_key $scheme$proxy_host$request_uri;
  • proxy_cache_use_stale:定义在哪些情况下可以使用过期的缓存内容。
    • proxy_cache_use_stale error timeout invalid_header http_500;
  • proxy_cache_min_uses:定义缓存项在被视为“热门”并被存储到缓存中之前,至少应被请求多少次。
    • proxy_cache_min_uses 1;
  • proxy_no_cache:定义哪些请求不应被缓存。
    • proxy_no_cache $cookie_nocache $arg_nocache$arg_comment;

配置示例

基本缓存配置

# 定义缓存路径
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;

# 在 location 中启用缓存
location / {
    proxy_cache my_cache;
    proxy_cache_valid 200 302 10m;
    proxy_cache_valid 404 1m;
    proxy_cache_key "$scheme$request_method$host$request_uri";
    proxy_cache_bypass $http_pragma $http_authorization;
    proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
    proxy_pass http://backend;
}
高级缓存配置

# 启用缓存锁防止缓存击穿
proxy_cache_lock on;
proxy_cache_lock_timeout 5s;

# 设置最小使用次数
proxy_cache_min_uses 3;

# 缓存路径配置
proxy_cache_path /var/cache/nginx 
    levels=1:2 
    keys_zone=STATIC:10m 
    inactive=24h 
    max_size=1g;
注意事项
  1. 缓存键设计: proxy_cache_key 的设计直接影响缓存的命中率,需要根据业务需求合理设计
  2. 缓存时间: proxy_cache_valid 需要根据内容的更新频率来设置
  3. 缓存大小: proxy_cache_pathmax_size 需要根据服务器磁盘空间来设置
  4. 缓存锁: 在高并发场景下,建议启用 proxy_cache_lock 防止缓存击穿
  5. 过期缓存: proxy_cache_use_stale 可以在后端服务异常时提供降级服务

三、实例演示

以下是一个简单的Nginx配置示例,开启了Proxy Cache功能,并对缓存策略进行了优化。

    http {
        proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
        server {
            listen 80;
            server_name example.com;
            location / {
                proxy_pass http://backend_server;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

              # 设置页面不缓存
                if ($request_filename ~* \.(html|htm)$) {
                    add_header         Cache-Control "no-store, no-cache, must-revalidate, private, proxy-revalidate, max-age=0" always;
                    add_header         Pragma "no-cache" always;
                    add_header         Last-Modified $date_gmt always;
                    add_header         ETag "" always; 
                    add_header         Expires 0;
                    expires off;
              }
              # 静态资源缓存策略
              if ( $uri ~* "\.(gif|png|jpg|jpeg|bmp|swf)$" ) {
                  expires 1h;
              }
              if ( $uri ~* "\.(css|js)$" ) {
                  expires 30m;
              }
              if ( $uri ~* "\.(woff|woff2|ttf)$" ) {
                  expires 30d;
              }

              # 代理缓存配置        
              # 1、设置缓存区域名称
              proxy_cache my_cache;
              proxy_cache_key $host$uri$is_args$args;
              proxy_cache_valid 200 10m;     #200缓存10分钟
              proxy_cache_valid 304 5m;      #304缓存5分钟
              proxy_cache_valid 301 302 5m;  #301 302缓存5分钟
              proxy_cache_valid any 1m;      #其他未设置的状态码缓存1分钟
              proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
              proxy_cache_min_uses 3;

              # 缓存锁防止缓存击穿
              proxy_cache_lock on;
              proxy_cache_lock_timeout 5s;

              # 缓存绕过条件
              #proxy_cache_bypass $cookie_nocache $arg_nocache $arg_comment;
              proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;

              # 响应头
              add_header X-Cache $upstream_cache_status;
              proxy_ignore_headers Set-Cookie Cache-Control expires;
            }
        }
    }

四、优化缓存策略

合理设置缓存有效期:根据网站内容的更新频率,为不同的HTTP响应码设置合理的缓存有效期,避免缓存内容过期。

使用proxy_cache_use_stale:在某些情况下,即使缓存内容已经过期,仍然可以使用它作为临时响应。这可以减少对后端服务器的请求次数,提高网站性能。

控制缓存大小:根据服务器的磁盘空间和网络带宽,合理设置proxy_cache_path的max_size参数,以控制缓存大小,避免磁盘空间不足。

排除不必要的缓存:使用proxy_no_cache指令排除不需要缓存的请求

作者:Jeebiz  创建时间:2025-06-28 17:19
最后编辑:Jeebiz  更新时间:2025-06-29 00:57