fastcgi缓存是nginx层零依赖动态加速手段:先验证nginx -v含with-http_fastcgi_module,再在http块首行定义fastcgi_cache_path并授权www用户,接着设cache_key与valid规则,最后在location中启用phpcache并用bypass/no_cache排除登录态和动态请求。

FastCGI 缓存是 Nginx 层最直接、零依赖的动态页面加速手段——它不碰 PHP 代码,也不改数据库,只在请求入口处把 PHP-FPM 生成的 HTML 页面缓存成文件,后续相同请求直接返回,毫秒级响应。
确认模块已启用
这是所有配置的前提。执行命令验证:
nginx -V 2>&1 | grep with-http_fastcgi_module若无输出,说明缺失模块。宝塔用户建议重装 Nginx 1.24(勾选“编译安装”);源码部署需在 configure 时加入 --with-http_fastcgi_module。未启用该模块,任何 fastcgi_cache 指令都会报 unknown directive 错误。
定义缓存区(http 块内)
必须放在 nginx.conf 的 http { } 块开头位置,且早于所有 include 语句:
- fastcgi_cache_path /www/server/nginx/cache levels=1:2 keys_zone=phpcache:100m inactive=30m max_size=2g use_temp_path=off;
- keys_zone=phpcache 是缓存区唯一标识,后续 location 中必须严格一致
- max_size=2g 防止缓存占满磁盘;use_temp_path=off 减少 IO 延迟
- 目录需由 Nginx 工作用户(如 www)完全控制:chown -R www:www /www/server/nginx/cache
设置缓存策略与键规则
仍位于 http 块中,全局生效:
- fastcgi_cache_key "$scheme$request_method$host$request_uri"; —— 确保 GET /product/123 和 GET /product/456 不互相覆盖
- fastcgi_cache_valid 200 302 10m; —— 正常响应缓存 10 分钟
- fastcgi_cache_valid 404 1m; —— 404 页面也缓存,减轻后端压力
- fastcgi_ignore_headers Cache-Control Expires Set-Cookie; —— 强制忽略 PHP 返回的禁用缓存头(否则缓存永远写不进)
在站点 location 中启用并过滤
进入网站配置文件,在 location ~ \.php$ { } 区块内添加:
- fastcgi_cache phpcache; —— 引用前面定义的 keys_zone 名称
- fastcgi_cache_bypass $cookie_session $arg_nocache; —— 有登录态或带 ?nocache=1 的请求不读缓存
- fastcgi_no_cache $cookie_session $arg_nocache; —— 同样条件,也不写入缓存
- 搭配日志格式可监控命中率:log_format cache_log "... cache:$upstream_cache_status";
不复杂但容易忽略:缓存是否生效,关键看三件事——模块存在、目录权限正确、bypass/no_cache 条件没误拦。电商商品页、CMS 文章列表这类读多写少的页面,开启后 QPS 提升 3–5 倍很常见。











