How to Automate Daily Nginx Log Rotation with a Bash Script
This guide explains how to automatically rotate Nginx logs each day by renaming the current log file at midnight, creating dated backup directories, and signaling the Nginx master process with USR1 using a simple Bash script scheduled via a cron job.
nginx's log file does not rotate automatically, so a single large file can become hard to manage under high traffic.
Idea
At midnight rename the current log file to include the date, then create a new log file. Use a scheduled task (cron) to run a script that performs the rename and signals the Nginx master process with the USR1 signal to reopen logs.
Implementation
#/bin/bash
# Path to backup logs
bakpath='/home/nginx/logs'
# Path to nginx logs
logpath='/usr/local/nginx/logs'
# Create year/month subdirectory in backup path
mkdir -p $bakpath/$(date +%Y)/$(date +%m)
# Move and rename access log
mv $logpath/access.log $bakpath/$(date +%Y)/$(date +%m)/access.$(date +%Y%m%d).log
# Move and rename error log
mv $logpath/error.log $bakpath/$(date +%Y)/$(date +%m)/error.$(date +%Y%m%d).log
# Send USR1 signal to nginx to reopen logs
kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`Schedule this script to run at 00:00 daily via crontab to maintain manageable log files.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
