- Check available disk space
df -h /- Verify gzip is installed
which gzipsudo cp /etc/logrotate.d/nginx /etc/logrotate.d/nginx.baksudo nano /etc/logrotate.d/nginxReplace contents with (log file extensions may vary on different servers; hence revise and edit where needed):
/etc/nginx/log/*.log /etc/nginx/log/*.access /etc/nginx/log/*.error /var/log/nginx/*.log {
daily
missingok
rotate 14
compress
# delaycompress # Uncomment this line to enable delaycompress (log files will be compressed / zipped starting from *.2 onwards)
notifempty
create 0640 www-data root
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 $(cat /var/run/nginx.pid)
endscript
}sudo chmod 640 /etc/nginx/log/*
sudo chown www-data:root /etc/nginx/log/*sudo logrotate -d /etc/logrotate.d/nginxsudo logrotate -vf /etc/logrotate.d/nginxls -lh /etc/nginx/log/sudo nano /usr/local/bin/nginx-log-cleanup.shPaste this into the file:
#!/bin/bash
# Number of days to keep logs
RETENTION_DAYS=30
# Log directories to clean
LOG_DIRS=(
"/var/log/nginx"
"/etc/nginx/log"
)
for DIR in "${LOG_DIRS[@]}"; do
find "$DIR" -type f -name "*.gz" -mtime +$RETENTION_DAYS -exec rm -f {} \;
donesudo chmod +x /usr/local/bin/nginx-log-cleanup.shsudo crontab -eAdd this line:
30 2 * * * /usr/local/bin/nginx-log-cleanup.sh >> /var/log/nginx-cleanup-cron.log 2>&1Check this log to ensure the cron job runs correctly:
tail -f /var/log/nginx-cleanup-cron.logThe cron expression 30 2 * * * breaks down as:
ββββββββββββββ Minute (0 - 59)
β ββββββββββββββ Hour (0 - 23)
β β ββββββββββββββ Day of Month (1 - 31)
β β β ββββββββββββββ Month (1 - 12)
β β β β ββββββββββββββ Day of Week (0 - 7) (Sunday = 0 or 7)
β β β β β
β β β β β
30 2 * * *
30β at 30 minutes past the hour2β at 2 AM*β every day of the month*β every month*β every day of the week
β This means the task runs at 2:30 AM every day.