安装 php-fpm 并修改 nginx.conf,在 location ~ \.php$ 中配置 fastcgi_pass、SCRIPT_FILENAME 和 include fastcgi_params。

PHP-FPM 服务状态与监听机制
确认 php-fpm 已启动且正在监听 127.0.0.1:9000。这是 Nginx 转发请求的基础条件。

systemctl status php-fpm 检查运行状态。若未运行,使用 systemctl start php-fpm 启动并设置开机自启。默认情况下,PHP-FPM 通过 TCP 端口 9000 监听本地连接。Nginx 必须将 PHP 请求发送到该端口才能触发解析。
Nginx location 块配置详解
在 /etc/nginx/conf.d/default.conf 或站点配置文件中添加 location ~ \.php$ 块,确保路径匹配正确。

server {
listen 80;
server_name localhost;
root /var/www/html;
index index.php index.html;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
# 保存后执行 nginx -t 测试配置,然后 systemctl reload nginx
访问 http://localhost/info.php 应显示 PHP 信息页。若出现 403,检查 SCRIPT_FILENAME 路径是否存在;若出现 502,检查 php-fpm
配置核心在于三个指令:fastcgi_pass 指定后端地址,SCRIPT_FILENAME 映射物理路径,include fastcgi_params 传递环境变量。缺少任一环节都会导致 403 或 502 错误。
SCRIPT_FILENAME 路径拼接陷阱
当网站根目录为 /var/www/html 时,$document_root$fastcgi_script_name 能准确指向文件。
p>若手动编写路径如 /usr/share/nginx/html$fastcgi_script_name,一旦部署目录变更,所有 PHP 文件将返回 403 Forbidden。务必使用变量动态拼接,避免硬编码绝对路径。此问题在容器化部署或自定义工作目录时尤为常见。