要設置 Nginx 日志輪轉以節省空間,請按照以下步驟操作:
sudo apt-get update
sudo apt-get install nginx
找到 Nginx 日志文件的位置。默認情況下,日志文件通常位于 /var/log/nginx/
目錄下,其中 access.log
是訪問日志,error.log
是錯誤日志。
使用 logrotate 工具來管理日志輪轉。logrotate 是一個用于管理日志文件的系統工具,可以自動壓縮、移動、刪除和郵件通知日志文件。首先,創建一個新的 logrotate 配置文件,例如 /etc/logrotate.d/nginx
:
sudo touch /etc/logrotate.d/nginx
sudo nano /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
missingok
rotate 7
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
}
這個配置文件表示:
daily
)missingok
)rotate 7
)compress
)delaycompress
)notifempty
)create 0640 www-data adm
)sharedscripts
和 postrotate
塊)保存并退出編輯器。
測試 logrotate 配置是否正確:
sudo logrotate -d /etc/logrotate.d/nginx
如果沒有錯誤,那么配置應該是正確的。
sudo systemctl enable logrotate
sudo systemctl start logrotate
現在,Nginx 日志文件將按照配置文件中的設置進行輪轉,從而節省磁盤空間。