In a cloud server, Nginx's access log is written to a unified log file by default, such as /var/log/nginx/access.log. However, if the website traffic is large, the log file will grow rapidly, which is not conducive to management and analysis. Therefore, regular segmentation (by day, hour, etc.) of log storage is a common optimization method. The following are several ways to implement Nginx access log segmentation:
Method 1: It is recommended to use logrotate to automatically segment logs
Logrotate is a built-in log management tool in Linux that can automatically archive, compress and delete old logs regularly.
Configure logrotate
Add or modify the following content in /etc/logrotate.d/nginx:
/var/log/nginx/access.log {
daily # Split by day (optional hourly, weekly, monthly)
rotate 7 # Keep 7 days of logs
missingok # Ignore non-existent log files
notifempty # Empty files are not processed
compress # Use gzip to compress logs
delaycompress # Delay compression for one day to prevent the log from being compressed while it is still being written
postrotate
systemctl reload nginx > /dev/null 2>&1 # Reload Nginx to use the new log file
endscript
}
Manually testing logrotate
sudo logrotate -f /etc/logrotate.d/nginx
Method 2: Manual shell script timed splitting
Applicable to scenarios that require customized log format or customized management.
Create a log splitting script
Create a new script /usr/local/bin/nginx_log_split.sh:
#!/bin/bash
# Define the log storage directory
LOG_DIR="/var/log/nginx"
DATE=$(date +%Y-%m-%d)
# Back up the current log
mv $LOG_DIR/access.log $LOG_DIR/access-$DATE.log
# Reopen the log file
kill -USR1 $(cat /run/nginx.pid)
kill -USR1 $(cat /run/nginx.pid) allows Nginx to reopen the log file without interrupting the service.
Give execution permission
chmod +x /usr/local/bin/nginx_log_split.sh
Configure crontab for scheduled execution
Edit crontab:
crontab -e
Add to:
0 0 * * * /usr/local/bin/nginx_log_split.sh
Indicates that log segmentation is run at midnight every day.
Method 3: Nginx automatically segments logs by day (based on variables)
If you want to segment logs by date directly in Nginx, you can use the $time_local variable.
Modify Nginx configuration
Open /etc/nginx/nginx.conf or site configuration file:
access_log /var/log/nginx/access-$time_iso8601.log;
However, Nginx does not support dynamic log file paths by default, so this method only works with OpenResty or specially compiled Nginx versions.