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$ {<br> include fastcgi_params;<br> fastcgi_pass 127.0.0.1:9000; # 或 unix:/run/php/php8.1-fpm.sock;<br> fastcgi_index index.php;<br> fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;<br>}登录后复制
-
fastcgi_param SCRIPT_FILENAME这一行特别重要——它告诉 PHP-FPM 实际要执行哪个文件路径,漏掉或写错会导致 502 或 “File not found” - 确保
root指令已正确定义(如root /var/www/html;),否则$document_root无法解析
验证与常见问题排查
改完配置后不要直接重启,先检查语法再重载:
标签: php centos html php8 nginx 处理器 ubuntu ai unix 配置文件 常见问题 gate
还木有评论哦,快来抢沙发吧~