温馨提示×

debian如何配置nginx日志

小樊
44
2026-09-07 09:13:35
栏目: 智能运维

在 Debian 上配置 Nginx 日志通常包括两部分:

  1. 访问日志(access_log)
  2. 错误日志(error_log)

下面按常见场景逐步说明。


一、Nginx 日志的默认位置

在 Debian 中,Nginx 默认日志目录为:

/var/log/nginx/

默认包含:

  • access.log:访问日志
  • error.log:错误日志

二、基本日志配置(推荐从这里开始)

1. 编辑 Nginx 主配置文件或站点配置

sudo nano /etc/nginx/nginx.conf

或某个站点配置(更常见):

sudo nano /etc/nginx/sites-available/default

2. 配置错误日志

httpserverlocation 块中均可:

error_log /var/log/nginx/error.log warn;

日志级别(从低到高):

debug < info < notice < warn < error < crit < alert < emerg

3. 配置访问日志

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 的访问日志(如静态资源)

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

六、修改日志后重载 Nginx

sudo nginx -t
sudo systemctl reload nginx

七、常见问题

1. 日志不更新?

  • 检查 nginx -t
  • 检查文件权限
  • 确认 logrotate 是否执行

2. 想按日期分割日志?

Nginx 本身不支持,可用:

  • logrotate
  • 或第三方模块(如 nginx-log-date-ext

如果你有具体需求(如 JSON 日志、按天切割、Docker 环境、负载均衡日志),可以告诉我,我可以给你更针对性的配置。

0