在 Debian 上配置 Nginx 日志通常包括两部分:
下面按常见场景逐步说明。
在 Debian 中,Nginx 默认日志目录为:
/var/log/nginx/
默认包含:
access.log:访问日志error.log:错误日志sudo nano /etc/nginx/nginx.conf
或某个站点配置(更常见):
sudo nano /etc/nginx/sites-available/default
在 http、server 或 location 块中均可:
error_log /var/log/nginx/error.log warn;
日志级别(从低到高):
debug < info < notice < warn < error < crit < alert < emerg
access_log /var/log/nginx/access.log;
在 http 块中定义:
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
然后引用:
access_log /var/log/nginx/access.log main;
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/example.access.log;
error_log /var/log/nginx/example.error.log;
location / {
root /var/www/example;
index index.html;
}
}
location ~* \.(jpg|png|css|js)$ {
access_log off;
}
Debian 默认使用 logrotate 管理 Nginx 日志。
查看配置:
cat /etc/logrotate.d/nginx
示例内容(系统自带):
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}
如需立即测试:
sudo logrotate -f /etc/logrotate.d/nginx
sudo nginx -t
sudo systemctl reload nginx
nginx -tlogrotate 是否执行Nginx 本身不支持,可用:
logrotatenginx-log-date-ext如果你有具体需求(如 JSON 日志、按天切割、Docker 环境、负载均衡日志),可以告诉我,我可以给你更针对性的配置。