Rotating Nginx Vhost Log Files Using Logrotate

Published December 5th, 2012

Web site access and error logs can grow out of control in size if not handled properly especially on medium to high traffic sites. In order to rotate logs kept for sites keeping separate log files from the Nginx logs themselves you can use the following script which can be executed by logrotate, which handles log management on most all *NIX types systems, to easily manage the rotation of your web site log files.

First open the file /etc/logrotate.d/nginx in your favorite text editor.

sudo nano /etc/logrotate.d/nginx

Then add the following text to this file being sure to set the correct path to the folder containing the log files to be managed at the beginning of the script.

/var/www/vhosts/*/logs/*.log {
    rotate 52
    create 0640 www-data adm
        if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
            run-parts /etc/logrotate.d/httpd-prerotate; \
        fi; \
        [ ! -f /var/run/ ] || kill -USR1 `cat /var/run/`

In a nutshell this script will rotate all *.log files in the directory specified every day and log files will be rotate 52 times before being removed.

A script such as the one above should be added to the file /etc/logrotate.d/nginx for each vhost you are hosting which store their logs separate from Nginx’s main logs in order to cut back on the space being used to store these log files.

The above is basically a copy of Nginx’s own log rotation script and can be tailored to fit your needs. For more information on logrotate as well as learn how to modify this script to fit your needs check out the logrotate man page found here.