用 NGINX 打造高性能 FastCGI 加速 `ngx_http_fastcgi_module`

一、安装与启用

bash 复制代码
# 在编译 NGINX 源码时加上:
./configure --with-http_fastcgi_module
make && sudo make install

# 或确保你使用的二进制已内置(大多数发行版都默认包含)
nginx -V | grep fastcgi

二、基础转发配置

nginx 复制代码
http {
  server {
    listen 80;
    server_name example.com;

    root /var/www/html;

    location ~ \.php$ {
      fastcgi_pass            unix:/run/php/php8.1-fpm.sock;
      fastcgi_index           index.php;
      include                 fastcgi_params;

      fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
      fastcgi_param QUERY_STRING     $query_string;
      fastcgi_param REQUEST_METHOD   $request_method;
      fastcgi_param CONTENT_TYPE     $content_type;
      fastcgi_param CONTENT_LENGTH   $content_length;
      fastcgi_param REDIRECT_STATUS  200;
    }
  }
}
  • fastcgi_pass:指定后端地址(TCP 或 Unix Socket)。
  • fastcgi_index :URI 以 / 结尾时,追加该脚本名。
  • fastcgi_param:设置环境变量传给后端。

三、缓冲与临时文件

3.1.打开/关闭缓冲

shell 复制代码
fastcgi_buffering on;   # 默认 on
# or
fastcgi_buffering off;  # 实时转发,不做缓冲

3.2.缓冲区大小与数量

shell 复制代码
fastcgi_buffer_size        16k;        # 初始 header 缓冲
fastcgi_buffers            8 32k;      # 读 body 时的内存缓冲
fastcgi_busy_buffers_size  64k;        # 正在向客户端发送时可占用的内存

3.3.临时文件设置

nginx 复制代码
fastcgi_temp_path       /var/cache/nginx/fastcgi_temp 1 2;  
fastcgi_max_temp_file_size 512m;
fastcgi_temp_file_write_size 32k;
  • fastcgi_temp_path:超出内存缓冲时写入磁盘。
  • fastcgi_max_temp_file_size:允许写入最大临时文件大小(0=禁用写盘)。
  • fastcgi_temp_file_write_size:每次写盘的块大小。

四、二级缓存(FastCGI Cache)

4.1.定义缓存路径

shell 复制代码
fastcgi_cache_path /var/cache/nginx/php_cache levels=1:2 \
    keys_zone=php_cache:128m inactive=30m max_size=5g;

4.2.在 Location 中启用

nginx 复制代码
location ~ \.php$ {
  fastcgi_cache           php_cache;
  fastcgi_cache_key       $scheme$host$request_uri;
  fastcgi_cache_valid     200 301 302 10m;
  fastcgi_cache_valid     404      1m;
  fastcgi_cache_methods   GET HEAD;
}

4.3.背景更新与过期使用

nginx 复制代码
fastcgi_cache_use_stale       error timeout updating http_500 http_503;
fastcgi_cache_background_update on;
  • use_stale updating:当条目在后台更新时,仍可返回旧缓存。
  • background_update:只触发后台刷新,不阻塞用户请求。

4.4.缓存锁

nginx 复制代码
fastcgi_cache_lock          on;
fastcgi_cache_lock_timeout  5s;
fastcgi_cache_lock_age      5s;
  • 避免缓存击穿:同一缓存键仅一条请求打到后端,其它请求排队等待或超时。

五、超时与失败切换

shell 复制代码
fastcgi_connect_timeout   5s;
fastcgi_read_timeout      60s;
fastcgi_send_timeout      60s;

fastcgi_next_upstream     error timeout invalid_header http_500 http_503;
fastcgi_next_upstream_tries   3;
fastcgi_next_upstream_timeout 30s;
  • 连接/读取/发送超时:防止挂起。
  • fastcgi_next_upstream:列出哪些场景下切换后端。
  • tries / timeout:限制切换次数与时长。

六、参数传递与路径拆分

6.1.PATH_INFO 支持

shell 复制代码
location ~ ^(.+\.php)(/.*)$ {
  fastcgi_split_path_info  ^(.+\.php)(/.*)$;
  fastcgi_param SCRIPT_FILENAME  $document_root$1;
  fastcgi_param PATH_INFO        $2;
  include fastcgi_params;
  fastcgi_pass   php-fpm;
}
  • fastcgi_split_path_info:正则拆分 URI,支持框架路由。

七、动态存储(fastcgi_store)

nginx 复制代码
location ~ \.php$ {
  # 反向缓存/保存原始文件
  fastcgi_store             on;
  fastcgi_store_access      user:rw group:r all:r;
  fastcgi_temp_path         /var/cache/nginx/php_store_temp;
  alias                     /var/www/html/;
}
  • fastcgi_store:将后端响应写入本地文件系统,适合缓存不变资源。

八、限速与连接管理

shell 复制代码
fastcgi_limit_rate         100k;     # 每请求最大读取速率
fastcgi_socket_keepalive   on;       # 与后端开启 TCP keepalive
fastcgi_bind               192.168.1.10 transparent;
  • fastcgi_limit_rate:防止后端过快/刷流量。
  • fastcgi_bind:指定本地出站 IP 用于与后端的连接。

九、最佳实践与调优

9.1. 缓冲策略

  • 小响应可全内存缓冲,增大 fastcgi_buffers;大文件开启写盘并调大 max_temp_file_size

9.2. 缓存合理性

  • 复杂登录或动态页面不缓存;仅对无用户差异或可共享资源启用。

9.3. 失败切换

  • 多 FPM 节点时务必配置 next_upstreamtriestimeout

9.4. 监控与日志

  • 通过 status 模块、access_log + $upstream_cache_status 监控缓存命中率与后端性能。

9.5. 安全防护

  • 配合 limit_exceptauth_basicdeny/allow 做访问控制;
  • 注意 fastcgi_param 不要泄露敏感路径或变量。

十、总结

ngx_http_fastcgi_module 功能丰富,从最基础的 FastCGI 转发,到缓冲、临时存储、缓存、失败切换、限速、存储......几乎覆盖了生产环境对动态脚本加速的所有需求。合理配置后,能够:

  • 提升并发吞吐:减轻后端压力
  • 优化延迟:靠本地缓存和缓冲平滑流量
  • 增强可用性:自动切换与 stale 服务兜底
  • 强化安全:精细化访问与速率控制

在高并发、微服务和多机房部署场景中,深度掌握并调优本模块,是打造稳定、高效 Web 架构的关键。祝你在实战中收获性能飞跃!

相关推荐
小妖66631 分钟前
mac 安装 nginx
运维·nginx·macos
Craze_rd32 分钟前
服务 HTTP 转 SRPC 技术方案
网络·网络协议·http·rpc·golang
卓码软件测评34 分钟前
第三方web测评机构:【WEB安全测试中HTTP方法(GET/POST/PUT)的安全风险检测】
前端·网络协议·安全·web安全·http·xss
Whitess00734 分钟前
Websocket链接如何配置nginx转发规则?
websocket·网络协议·nginx
智能化咨询4 小时前
基于网络原理——HTTP/HTTPS的Web服务搭建与核心技术实践
网络·http·https
小白考证进阶中6 小时前
终于赶在考试券过期前把Oracle OCP证书考下来了!
运维·数据库·oracle·dba·开闭原则·数据库管理员
keep__go7 小时前
postgresql9.2.4 跨版本升级14.6
linux·运维·数据库·postgresql
Doris_LMS7 小时前
Git的强软硬回退(三)
运维·服务器·数据库·git·idea
(Charon)7 小时前
基于 epoll 的高并发服务器原理与实现(对比 select 和 poll)
运维·服务器
Jtti7 小时前
在 Debian 系统上清理缓存的方式和具体操作方法
运维·缓存·debian