How to Rotate Nginx Logs: Simple Guide for Log Management
To rotate
nginx logs, use the logrotate tool with a configuration file specifying nginx log paths and rotation rules. Alternatively, send the nginx process a USR1 signal to reopen log files after rotation.Syntax
Log rotation for nginx is usually managed by logrotate. The key parts of a logrotate config for nginx logs are:
path: The log file location, e.g.,/var/log/nginx/access.log.rotate: Number of old logs to keep.daily,weekly, ormonthly: How often to rotate.missingok: Ignore if log file is missing.notifempty: Do not rotate empty logs.postrotate: Commands to run after rotation, usually to tell nginx to reopen logs.
conf
/var/log/nginx/*.log { daily missingok rotate 14 compress delaycompress notifempty create 0640 www-data adm sharedscripts postrotate kill -USR1 $(cat /run/nginx.pid) endscript }
Example
This example shows a logrotate configuration file for nginx logs that rotates logs daily, keeps 14 days of logs, compresses old logs, and signals nginx to reopen logs after rotation.
conf
/var/log/nginx/*.log { daily missingok rotate 14 compress delaycompress notifempty create 0640 www-data adm sharedscripts postrotate kill -USR1 $(cat /run/nginx.pid) endscript }
Output
Logs in /var/log/nginx/access.log and error.log are rotated daily.
Old logs are compressed and kept for 14 days.
Nginx receives USR1 signal to reopen logs after rotation.
Common Pitfalls
Common mistakes when rotating nginx logs include:
- Not signaling nginx to reopen logs after rotation, causing nginx to keep writing to old files.
- Incorrect permissions on new log files, preventing nginx from writing.
- Forgetting to include
sharedscriptswhen multiple log files are rotated. - Using
systemctl reload nginxinstead of sendingUSR1signal, which is less efficient.
conf
Wrong way (no postrotate signal): /var/log/nginx/*.log { daily rotate 7 compress } Right way (with postrotate signal): /var/log/nginx/*.log { daily rotate 7 compress postrotate kill -USR1 $(cat /run/nginx.pid) endscript }
Quick Reference
| Directive | Description |
|---|---|
| daily | Rotate logs every day |
| rotate 14 | Keep 14 old log files |
| compress | Compress old logs to save space |
| notifempty | Do not rotate empty logs |
| missingok | Ignore missing log files |
| create 0640 www-data adm | Create new log files with permissions and ownership |
| sharedscripts | Run postrotate script once for all logs |
| postrotate ... endscript | Commands to run after rotation, e.g., signal nginx |
Key Takeaways
Use logrotate with a config file to automate nginx log rotation.
Always signal nginx with USR1 after rotating logs to reopen files.
Set correct permissions on new log files to avoid write errors.
Include sharedscripts in logrotate config when rotating multiple logs.
Avoid using full nginx reload; USR1 signal is lighter and safer.