Add some configuration items to the Nginx configuration file to output PHP error log files. Normally, the Nginx configuration file on CentOS systems is saved in /etc/nginx/nginx.conf. Usually located at the top of the file, you can find the configuration section of the http module in the file and add the following configuration item:
http { ... server { ... 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; # error log fastcgi_param PHP_VALUE "error_log=/var/log/nginx/php_errors.log"; } ... } ... }
This configuration item will only be applied when the accessed URL ends with .php, that is, using location ~.php$. The address and port of the PHP FastCGI server are set in fastcgi_pass. fastcgi_param is used to set the parameters of PHP, where SCRIPT_FILENAME specifies the path and file name of the PHP script. To use the default FastCGI parameters, fastcgi_params needs to be included in Nginx. The last line adds fastcgi_param PHP_VALUE "error_log=/var/log/nginx/php_errors.log";, which means recording PHP error information to the /var/log/nginx/php_errors.log file.
Create a log file to record PHP error information. This is a step required after configuring Nginx. Assume that we want to save the log file to /var/log/nginx/php_errors.log. We can use the following command to create the file:
sudo touch /var/log/nginx/php_errors.log
Then use the following command to modify the owner and permissions of the file:
sudo chown nginx:nginx /var/log/nginx/php_errors.log sudo chmod 644 /var/log/nginx/php_errors.log
When testing, you can create a PHP script and an error occurs, for example:
<?php echo 1/0; ?>
Save this script as test.php, and then place it in In the web root directory of Nginx, for example /usr/share/nginx/html/test.php. When you visit http://localhost/test.php, you will find a PHP error. Then use the following command to view the contents of the log file:
sudo tail /var/log/nginx/php_errors.log
If everything is normal, you should see an error message similar to the following:
[17-Oct-2021 20:52:42 UTC] PHP Warning: Division by zero in /usr/share/nginx/html/test.php on line 2
The above is the detailed content of How to output php error log file in nginx. For more information, please follow other related articles on the PHP Chinese website!