Config logrotate for nginx with custom log path

Logrotate is so easy

If you have high traffic website, you will have larger and larger log files. Website logs are important and we need keep it for further investigation or reporting.

Luckily we can easily use logrotate to automatically archive the log files. Logrotate comes as default for many Linux distribution, such as Debian-based or CentOS.

The default nginx config for logrotate looks like this

/var/log/nginx/*log {
    create 0600 root root
    daily
    rotate 10
    missingok
    notifempty
    compress
    sharedscripts
    postrotate
        /bin/kill -USR1 `cat /run/nginx.pid 2>/dev/null` 2>/dev/null || true
    endscript
}

I often use nginx in custom path: 1 folder - 1 site.
For example

/var/log/nginx/siteA.com/access.log
/var/log/nginx/siteB.net/access.log

My logrotate therefore will look like below. I also write detail description on each line, for your convenience :)

/var/log/nginx/*/*log {
    # New file will be created with strict mode
    create 0600 root root
    # Rotate log file for every 7 days
    weekly
    # Keeps 52 last files only
    rotate 52
    # If the log file is missing, go on to the next one
    missingok
    # Do not rotate the log if it is empty
    notifempty
    # Leave the current file and the last single file unarchived (compress all others)
    delaycompress
    # Run this script only once, even though the pattern matches multiple files
    sharedscripts
    postrotate
        # After rotating, new log file created so we tell nginx to write to new log file
        if [ -f /var/run/nginx.pid ]; then
            /etc/init.d/nginx configtest && /etc/init.d/nginx restart > /dev/null
        fi
    endscript
}

Logrotate service, by default, run daily at 2AM. Our log files will be handled very well as this:

access.log
access.log.1
access.log-20151007.gz
access.log-20151008.gz
access.log-20151009.gz
access.log-20151010.gz