Introduction

Nginx is a high-performance web server and reverse proxy server. Proper logging and log rotation are essential for monitoring and maintaining the health of your web server. In this guide, we'll walk through the steps to configure logging and log rotation in Nginx on an Ubuntu VPS.

Prerequisites

Before proceeding, ensure you have:

  1. An Ubuntu VPS with Nginx installed

Steps to Configure Logging and Log Rotation in Nginx

    1. Configure Logging: Edit the Nginx configuration file to configure logging:
sudo nano /etc/nginx/nginx.conf

Add or modify the following lines in the http block to configure logging:

http {
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;
}
    1. Save and Close the File: Save the changes and close the file.
    2. Configure Log Rotation: Create a new log rotation configuration file for Nginx:
sudo nano /etc/logrotate.d/nginx

Add the following lines to configure log rotation:

/var/log/nginx/*.log {
    daily
    missingok
    rotate 52
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    prerotate
        if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
            run-parts /etc/logrotate.d/httpd-prerotate; \
        fi \
    endscript
    postrotate
        invoke-rc.d nginx rotate >/dev/null 2>&1
    endscript
}
    1. Save and Close the File: Save the changes and close the file.
    2. Restart Nginx: Restart the Nginx service to apply the changes:
sudo systemctl restart nginx

Conclusion

Congratulations! You have successfully configured logging and log rotation in Nginx on your Ubuntu VPS. Your Nginx logs will now be rotated regularly, ensuring efficient log management and monitoring.

Was this answer helpful? 0 Users Found This Useful (0 Votes)