为了在Linux系统上定期清理Nginx日志,可以使用cron定时任务来自动执行日志清理脚本。以下是详细步骤:
1. 创建日志清理脚本
首先,创建一个脚本,用于归档和清理旧的Nginx日志。例如,将其命名为
/usr/local/bin/cleanup_nginx_logs.sh
#!/bin/bash
# Directory where Nginx logs are stored
LOG_DIR="/var/log/nginx"
# Number of days to keep logs
DAYS_TO_KEEP=30
# Archive directory
ARCHIVE_DIR="/var/log/nginx/archive"
# Create archive directory if it doesn't exist
mkdir -p $ARCHIVE_DIR
# Find and move old log files to the archive directory
find $LOG_DIR -type f -name '*.log' -mtime +$DAYS_TO_KEEP -exec mv {} $ARCHIVE_DIR \;
# Compress archived logs
find $ARCHIVE_DIR -type f -name '*.log' -exec gzip {} \;
# Remove compressed logs older than DAYS_TO_KEEP
find $ARCHIVE_DIR -type f -name '*.gz' -mtime +$DAYS_TO_KEEP -exec rm {} \;
# Reload Nginx to reopen log files
systemctl reload nginx