Blog / Linux/ Automated Nginx Log Rotation and Archiving Setup (Year/Month/Day Directory Storage)

Automated Nginx Log Rotation and Archiving Setup (Year/Month/Day Directory Storage)

Nginx日志自动切割与归档配置教程(按年/月/日目录存储)

Nginx Log Rotation and Archiving Configuration Guide

This guide will help you configure an automated script to rotate Nginx logs. The script will split logs daily, store them in a year/month/day directory structure, and automatically clean up old logs.

Step 1: Download and Extract the Script

Run the following commands to download the script to /root/, extract it, and open it for editing.

cd /root/
wget https://wpquicksearch.com/wp-content/uploads/oldimg/2015/08/cut_nginx_logs.tar.gz
tar -xzvf cut_nginx_logs.tar.gz
vi cut_nginx_logs.sh

Step 2: Edit the Script Configuration

In the vim editor, press i to enter insert mode. Locate and modify the following key parameters for your environment:

# Set the Nginx log directory path (default is for LNMP package; modify as needed)
log_files_path="/home/wwwlogs/"
# Logs will be stored in a "year/month/" directory structure with filename "originalname_YYYYMMDD.log"
log_files_dir=${log_files_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")
# Set log names to rotate (without .log suffix), separate multiple names with spaces
log_files_name=(access xxx.com)
# Set the Nginx executable path
nginx_sbin="/usr/local/nginx/sbin/nginx"
# Set the number of days to keep logs
save_days=30

After editing, press ESC to exit insert mode, then type :wq to save and quit vim.

Step 3: Configure the Crontab Scheduled Task

Run the following command to edit the current user's crontab:

crontab -e

Press i to enter insert mode and add the following line (e.g., to run daily at 5:00 AM):

00 05 * * * /bin/bash /root/cut_nginx_logs.sh

After adding the line, press ESC, then type :wq to save and exit.

Completion and Verification

The configuration is now complete. The system will automatically run the log rotation task daily at 05:00, archiving logs to the corresponding year/month/ directory and deleting logs older than save_days (default 30 days).

Note: Ensure the log_files_path and nginx_sbin paths in the script match your server's actual paths. After initial setup, it's recommended to run the script manually once to verify it works:

/bin/bash /root/cut_nginx_logs.sh

Post a Comment

Your email will not be published. Required fields are marked with *.