在 Linux 下让 Nginx 运行 PHP 文件,核心是配置 Nginx 将 .php 请求转发给 PHP-FPM 进程。只需确保 Nginx 的 location ~ \.php$ 块中 fastcgi_pass 指向正确的 Unix Socket 或 TCP 地址,并设置 include fastcgi_params 即可。

Nginx 与 PHP-FPM 通信机制
Nginx 本身不处理 PHP 代码,它作为反向代理,通过 FastCGI 协议将 PHP 请求传递给 PHP-FPM。PHP-FPM 解析代码后返回 HTML 结果。两者通常通过 Unix Socket(如 /run/php/php8.1-fpm.sock)通信,性能优于 TCP。

关键配置点:必须匹配 .php 后缀,避免静态文件被错误执行。
当用户访问 index.php 时,Nginx 根据正则表达式定位到 PHP 处理器。若未正确配置 fastcgi_pass,会返回 502 Bad Gateway。需检查 PHP-FPM 服务是否启动,且 Socket 文件权限允许 Nginx 用户(如 www-data)访问。
完整 Nginx 站点配置示例
以下配置适用于 Debian/Ubuntu 系统,使用 PHP 8.1。将代码保存为 /etc/nginx/sites-available/default,并通过 sudo nginx -t && sudo systemctl reload nginx 重载生效。

server {
listen 80;
server_name localhost;
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.1-fpm.sock;
}
}
# 创建测试文件
mkdir -p /var/www/html
echo '<?php phpinfo(); ?>' > /var/www/html/info.php
# 验证配置并重载
sudo nginx -t
sudo systemctl reload nginx
# 测试访问
curl http://localhost/info.php | head -n 5
执行 curl 命令后,若输出包含 “PHP Version” 字样,说明 PHP 已成功由 FPM 处理。若返回纯文本源码,则 Nginx 未正确转发请求;若报错 502,请检查 fastcgi_pass 路径是否与 php-fpm.conf 中 listen 一致。
该配置监听 80 端口,根目录为 /var/www/html。重点在于 location ~ \.php$ 块,它将请求转发给本地 Socket,并包含标准 FastCGI 参数文件。
常见 403 与 502 错误排查
若访问 PHP 页面出现 403 Forbidden,通常因 try_files $uri =404; 未正确处理或文件权限不足。若出现 502 Bad Gateway,则多为 PHP-FPM 未启动或 Socket 路径不匹配。
检查 systemctl status php8.1-fpm 确认服务状态。查看 Nginx 错误日志 /var/log/nginx/error.log 获取具体原因。确保 fastcgi_param SCRIPT_FILENAME 指向实际文件路径,而非 URI。