Ubuntu PHP配置错误的快速排查与修复
一、定位问题最快路径
php -v、php -m、php --inisudo systemctl status apache2 或 sudo systemctl status nginxsudo tail -f /var/log/apache2/error.logsudo tail -f /var/log/nginx/error.logsudo tail -f /var/log/php/*-fpm.logsudo systemctl restart apache2sudo systemctl restart nginxsudo systemctl restart php<版本>-fpm(如:php8.1-fpm)sudo apt-get install libapache2-mod-php<版本>sudo apt-get install php<版本>-gd二、Apache 与 PHP 模块的常见修复
sudo apt-get updatesudo apt-get install apache2 libapache2-mod-php<版本>sudo systemctl restart apache2sudo a2dismod mpm_event && sudo a2enmod mpm_preforksudo systemctl restart apache2libapache2-mod-php<版本>)三、Nginx + PHP-FPM 的常见修复
sudo apt-get install nginx php<版本>-fpmsudo systemctl enable --now php<版本>-fpm nginxlocation ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php<版本>-fpm.sock; }sudo systemctl status php<版本>-fpmsudo systemctl restart nginx php<版本>-fpm四、开启错误提示与定位语法错误
php --ini 显示的 Loaded Configuration Filephpinfo(); 中的 Loaded Configuration File/etc/php/<版本>/apache2/php.ini 或 /etc/php/<版本>/cli/php.inidisplay_errors = Onerror_reporting = E_ALLphp -l /path/to/file.phpdisplay_errors = On,仅在排错时临时启用五、高频场景与一键命令清单
| 场景 | 快速命令 |
|---|---|
| 查看 PHP 版本与已加载模块 | php -v、php -m |
| 找到 php.ini | php --ini |
| Apache 启动失败 | sudo systemctl status apache2;日志:sudo tail -f /var/log/apache2/error.log |
| Nginx + FPM 502/504 | sudo systemctl status php<版本>-fpm;日志:sudo tail -f /var/log/nginx/error.log /var/log/php/*-fpm.log |
| 安装 Apache 模块 | sudo apt-get install libapache2-mod-php<版本> && sudo systemctl restart apache2 |
| 安装扩展(如 GD) | `sudo apt-get install php<版本>-gd && sudo systemctl restart apache2 |
| 切换 MPM(事件→prefork) | sudo a2dismod mpm_event && sudo a2enmod mpm_prefork && sudo systemctl restart apache2 |
| FPM 无法连接 | 检查 socket:ls -l /var/run/php/php<版本>-fpm.sock;重启:sudo systemctl restart php<版本>-fpm |
| 语法快速检查 | php -l /var/www/html/index.php |
| 修改后重启 | Apache:sudo systemctl restart apache2;Nginx:sudo systemctl restart nginx;FPM:sudo systemctl restart php<版本>-fpm |