如何用nginx搭配php环境_nginxphp整合教程【配置】

Nginx 搭配 PHP 的核心是打通 Nginx → PHP-FPM → 执行 PHP 代码 → 返回结果的请求链路;需确认 PHP-FPM 运行、正确配置 fastcgi_pass 和 SCRIPT_FILENAME,并通过 phpinfo() 验证。

用 Nginx 搭配 PHP,核心是让 Nginx 把 PHP 请求(通常是 .php 文件)正确转发给 PHP 处理器(如 PHP-FPM),而不是自己尝试去解析。关键不在“安装”,而在“打通请求链路”——Nginx → PHP-FPM → 执行 PHP 代码 → 返回结果。

确认 PHP-FPM 已就绪

Nginx 本身不解析 PHP,必须依赖 PHP-FPM(FastCGI Process Manager)。先检查它是否运行:

  • 运行 systemctl status php-fpm(CentOS/RHEL)或 systemctl status php8.1-fpm(Ubuntu/Debian,版本号按实际调整)
  • 若未启动,执行 systemctl start php-fpm 并设为开机自启:systemctl enable php-fpm
  • 默认监听地址通常为 127.0.0.1:9000 或 Unix socket(如 /run/php/php8.1-fpm.sock),可在 /etc/php/*/fpm/pool.d/www.conf 中查 listen =

配置 Nginx 的 server 块支持 PHP

在站点的 Nginx 配置文件(如 /etc/nginx/conf.d/example.com.conf/etc/nginx/sites-enabled/default)中,确保 location 块能识别并代理 PHP 请求:

  • 添加或确认存在匹配 .php 的 location 块,例如:
    location ~ \.php$ {
    include fastcgi_params;
    fastcgi_pass 127.0.0.1:9000; # 或 unix:/run/php/php8.1-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
  • fastcgi_param SCRIPT_FILENAME 这一行特别重要——它告诉 PHP-FPM 实际要执行哪个文件路径,漏掉或写错会导致 502 或 “File not found”
  • 确保 root 指令已正确定义(如 root /var/www/html;),否则 $document_root 无法解析

验证与常见问题排查

改完配置后不要直接重启,先检查语法再重载:

  • 执行 nginx -t 确认配置无误
  • 执行 systemctl reload nginx 生效(避免中断服务)
  • 在网站根目录放一个 info.php

    访问 http://your-domain/info.php,能看到 PHP 信息页即成功
  • 若报 502 Bad Gateway:检查 PHP-FPM 是否运行、fastcgi_pass 地址是否匹配、socket 文件权限(尤其用 Unix socket 时,Nginx worker 用户需有读写权限)
  • 若报 File not found:重点核对 SCRIPT_FILENAMEroot 路径是否一致,注意末尾斜杠和大小写

不复杂但容易忽略——只要 Nginx 能把请求准确递给 PHP-FPM,再由 PHP-FPM 找到对应文件执行,整个链路就通了。