Nginx如何設(shè)置自動清理日志?
作者:管理員 來源:互聯(lián)網(wǎng) 發(fā)布時(shí)間:2025-11-10 10:10:24 點(diǎn)擊數(shù):0
在Nginx中,日志文件(包括訪問日志和錯(cuò)誤日志)會不斷增長,如果不進(jìn)行清理,可能會占用大量磁盤空間。以下是如何設(shè)置自動清理Nginx日志的幾種方法:
方法一:使用 logrotate
1:創(chuàng)建 logrotate 配置文件
sudo nano /etc/logrotate.d/nginx
2:添加以下配置內(nèi)容
/var/log/nginx/*.log {
daily
missingok
rotate 52
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 `cat /var/run/nginx.pid`
fi
endscript
}配置參數(shù)說明:
daily:每天輪轉(zhuǎn)
missingok:如果日志文件不存在也不報(bào)錯(cuò)
rotate 52:保留52個(gè)備份文件(約2個(gè)月)
compress:壓縮舊的日志文件
delaycompress:延遲壓縮前一個(gè)日志文件
notifempty:空文件不輪轉(zhuǎn)
create 0640 www-data adm:創(chuàng)建新文件的權(quán)限和屬主
postrotate:輪轉(zhuǎn)后執(zhí)行的命令,重新打開日志文件
方法二:手動配置更頻繁的輪轉(zhuǎn)
如果需要更頻繁的輪轉(zhuǎn),可以修改配置:
/var/log/nginx/*.log {
hourly
missingok
rotate 168 # 保留7天的每小時(shí)日志
compress
delaycompress
notifempty
create 0640 nginx nginx
sharedscripts
postrotate
/bin/kill -USR1 $(cat /var/run/nginx.pid 2>/dev/null) 2>/dev/null || true
endscript
}方法三:使用 crontab 自定義清理腳本
1:創(chuàng)建清理腳本
sudo nano /usr/local/bin/nginx_log_clean.sh
#!/bin/bash # 清理超過30天的Nginx日志文件 find /var/log/nginx/ -name "*.log.*" -type f -mtime +30 -delete # 重新加載Nginx(如果需要) # systemctl reload nginx
2:給腳本執(zhí)行權(quán)限
sudo chmod +x /usr/local/bin/nginx_log_clean.sh
3:添加到 crontab
sudo crontab -e
添加以下行(每天凌晨2點(diǎn)執(zhí)行)
0 2 * * * /usr/local/bin/nginx_log_clean.sh
推薦使用 方法一(logrotate),這是最標(biāo)準(zhǔn)且可靠的日志管理方式。
上一篇:Windows如何遠(yuǎn)程國產(chǎn)麒麟操作系統(tǒng)
下一篇:Linux系統(tǒng)命令:主機(jī)狀態(tài)監(jiān)控、環(huán)境變量、文件傳輸及壓縮和解壓縮
相關(guān)內(nèi)容:
