How to set up Nginx to handle PHP-FPM custom error logs and log rotation?

To set up Nginx to handle PHP-FPM custom error logs and log rotation, you'll need to follow these steps:

  1. Edit the php-fpm.conf file: Open the PHP-FPM configuration file in a text editor, usually located at /etc/php-fpm.conf or /etc/php/7.x/fpm/php-fpm.conf. Uncomment and modify the following lines:

    php_flag[display_errors] = off php_admin_value[error_log] = /var/log/php-fpm/error.log

    This will disable error display and set the error log file path to /var/log/php-fpm/error.log.

  2. Create the error log directory: Create the directory where the PHP-FPM error log will reside. Run the following command:

    sudo mkdir -p /var/log/php-fpm

    Adjust the directory path if necessary based on your configuration.

  3. Create a new Nginx server block: Open your Nginx configuration file for the site you want to handle PHP-FPM error logs. This file is typically located at /etc/nginx/sites-available/your-site.conf. Inside the server block, add the following lines:

    location ~ \.php$ { fastcgi_pass unix:/var/run/php/php7.x-fpm.sock; fastcgi_param PHP_VALUE "error_log=/var/log/php-fpm/your-site.log"; ... }

    Replace 7.x with your specific PHP version. Adjust the error log path and filename (your-site.log) as needed.

  4. Create a logrotate configuration file: Create the logrotate configuration file /etc/logrotate.d/php-fpm with the following contents:

    /var/log/php-fpm/*.log { weekly missingok rotate 52 compress delaycompress notifempty create 644 www-data www-data }

    This file will rotate the PHP-FPM error logs on a weekly basis.

  5. Restart PHP-FPM and Nginx: After making the changes, restart PHP-FPM and Nginx to apply the new settings. Use the following commands:

    sudo systemctl restart php7.x-fpm sudo systemctl restart nginx

    Replace 7.x with your specific PHP version.

Your Nginx should now be set up to handle PHP-FPM custom error logs and log rotation. Errors will be logged to the specified location, and log rotation will occur according to the logrotate configuration.