温馨提示×

php-fpm与nginx如何配合使用

小樊
31
2025-12-06 14:51:45
栏目: 编程语言

Nginx 与 PHP-FPM 的协作原理与适用场景

  • Nginx 负责接收 HTTP 请求、处理静态资源,并将以 .php 结尾的动态请求通过 FastCGI 协议转发给 PHP-FPM
  • PHP-FPM(FastCGI Process Manager) 维护一个 master/worker 进程池来执行 PHP 脚本并把结果返回给 Nginx。
  • 二者解耦,便于独立扩展与维护;同机部署时常用 Unix Domain Socket(性能略优)或 TCP Socket 127.0.0.1:9000(跨机/容器更灵活)进行通信。

快速上手步骤 Ubuntu 20.04/22.04

  • 安装组件
    • sudo apt update && sudo apt install nginx php-fpm
  • 配置 PHP-FPM
    • 编辑 /etc/php/8.x/fpm/pool.d/www.conf(将 8.x 替换为实际版本),常用两种监听方式:
      • Unix 套接字:listen = /run/php/php8.x-fpm.sock
      • TCP 端口:listen = 127.0.0.1:9000
    • 启动并设为开机自启:sudo systemctl enable --now php8.x-fpm
  • 配置 Nginx
    • 编辑 /etc/nginx/sites-available/default,示例:
      • server { listen 80; server_name your_domain_or_ip; root /var/www/html; index index.php index.html;
        location / { try_files $uri $uri/ =404; }
        location ~ .php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php8.x-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; }
        location ~ /.ht { deny all; } }
  • 校验与生效
    • sudo nginx -t && sudo systemctl restart nginx
  • 验证
    • 在站点根目录创建 /var/www/html/info.php
    • 访问 http://your_domain_or_ip/info.php,看到 PHP 信息页即成功(测试后建议删除该文件)。

CentOS 7/8 与 RHEL 的要点

  • 安装组件
    • sudo yum install epel-release && sudo yum install nginx php-fpm
  • 配置 PHP-FPM
    • 编辑 /etc/php-fpm.d/www.conf(或 /etc/php-fpm.conf):
      • listen = /run/php-fpm/www.sock127.0.0.1:9000
    • 启动并设为开机自启:sudo systemctl enable --now php-fpm
  • 配置 Nginx
    • 编辑 /etc/nginx/nginx.conf/etc/nginx/conf.d/default.conf,在 server 块中添加:
      • location ~ .php$ { fastcgi_pass unix:/run/php-fpm/www.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; }
  • 校验与生效
    • sudo nginx -t && sudo systemctl restart nginx
  • 验证
    • 站点根目录(常见为 /usr/share/nginx/html)放置 info.php 并访问测试。

常见故障排查与优化

  • 502 Bad Gateway / 504 Gateway Timeout
    • 检查 Nginx 错误日志(/var/log/nginx/error.log)与 PHP-FPM 错误日志(/var/log/php-fpm.log 或 pool 日志)。
    • 核对 fastcgi_pass 地址与 PHP-FPM 的 listen 一致;确认 PHP-FPM 进程存活且未达 pm.max_children 上限。
    • 504 多与 request_terminate_timeout / pm.process_idle_timeout 或后端慢脚本相关,适当调优超时与脚本性能。
  • 权限与路径
    • 确保 Nginx worker 进程用户(常见为 www-datanginx)对 socket 文件与站点目录有读/执行权限;
    • 必须设置 SCRIPT_FILENAME $document_root$fastcgi_script_name,否则会报 “No input file specified”。
  • 静态资源与路由
    • 优先由 Nginx 直接服务静态文件;PHP 路由(如前端控制器)需配合 try_files $uri $uri/ /index.php?$query_string;
  • 安全与运维
    • 删除 info.php 等敏感文件;限制 .ht 访问;仅开放 80/443;为域名配置 HTTPS/TLS(可用 certbot 自动申请与续期);定期更新系统与组件。

0