要在 Nginx 环境中正确输出 PHP 错误日志,需要同时配置 PHP 和 Nginx 的相关设置。以下是详细的配置方法:
error_log = /var/log/php_errors.log
log_errors = On
display_errors = Off # 生产环境建议关闭
编辑 /etc/php-fpm.conf
或 /etc/php-fpm.d/www.conf
:
catch_workers_output = yes
php_admin_value[error_log] = /var/log/php-fpm/error.log
php_admin_flag[log_errors] = on
在 server 块中添加以下配置:
server {
# ... 其他配置 ...
# 捕获 PHP 错误日志
fastcgi_intercept_errors on;
fastcgi_param PHP_VALUE "error_log=/var/log/nginx/php_errors.log";
fastcgi_param PHP_ADMIN_VALUE "log_errors=On";
# 可选:设置错误页面
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
sudo touch /var/log/php_errors.log
sudo chown www-data:www-data /var/log/php_errors.log # 根据实际用户调整
sudo chmod 666 /var/log/php_errors.log
sudo systemctl restart php-fpm
sudo systemctl restart nginx
创建测试 PHP 文件:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
trigger_error("This is a test error", E_USER_NOTICE);
检查日志文件是否记录了错误信息。
fastcgi_param PHP_VALUE "error_log=/var/log/nginx/$host-php_errors.log";
创建 /etc/logrotate.d/php
文件:
/var/log/php_errors.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 640 www-data adm
sharedscripts
postrotate
/usr/lib/php/php-fpm-reopenlogs
endscript
}
通过以上配置,PHP 错误日志将会被正确记录到指定文件中,便于排查问题。