How to Automate Daily Nginx Log Rotation with a Simple Shell Script
This guide explains why rotating Nginx access logs is essential for maintainability and demonstrates a straightforward shell script plus a cron job to split logs by day, ensuring smooth log management and easy analysis.
Introduction
By default Nginx writes all access logs to a single file (access.log), which can become large and hard to analyze over time. Rotating logs daily or hourly is necessary, and this article shows how to achieve daily rotation using a shell script.
Detailed Tutorial
Log Rotation Script
# cat /scripts/cut_nginx_log.sh
#!/bin/bash
Date=`date +%Y%m%d -d -1day`
BaseDir="/application/nginx"
NginxLogDir="${BaseDir}/logs"
LogName="access_www"
[ -d $NginxLogDir ] && cd $NginxLogDir || exit 1
[ -f ${LogName}.log ] || exit 1
/usr/bin/mv ${LogName}.log ${Date}_${LogName}.log
$BaseDir/sbin/nginx -s reloadThe script renames the currently written access log to a date‑prefixed file and then gracefully reloads Nginx to start a new log file.
Set Up a Cron Job
# vim /var/spool/cron/root
5 0 * * * /bin/sh /scripts/cut_nginx_log.sh >/dev/null 2>&1This schedules the script to run daily at 00:05.
Log Rotation Demonstration
# Before rotation
[root@www ~]# ls /application/nginx/logs/
access.log access_www.log error.log nginx.pid
# Current date
[root@www ~]# date +%F
2023-01-17
# Run script manually
[root@www ~]# sh /scripts/cut_nginx_log.sh
# After rotation
[root@www ~]# ls /application/nginx/logs/
20230116_access_www.log access.log access_www.log error.log nginx.pid
# Simulate next day
[root@www ~]# date -s '2023/01/18'
Fri Jan 18 00:00:00 CST 2023
# Run script again
[root@www ~]# sh /scripts/cut_nginx_log.sh
# After second rotation
[root@www ~]# ls /application/nginx/logs/
20230116_access_www.log 20230117_access_www.log access.log access_www.log error.log nginx.pidCommon Nginx log collection and analysis tools include rsyslog, awstats, flume, ELK, and Storm. Readers are encouraged to explore these tools further.
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.
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
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.
