Operations 2 min read

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.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
How to Automate Daily Nginx Log Rotation with a Bash Script

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

OperationsNginxSysadmincronBashlog rotation
Java High-Performance Architecture
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.