温馨提示×

debian nginx日志如何配置

小樊
43
2026-09-28 11:39:03
栏目: 智能运维

在 Debian 系统上,Nginx 的日志配置主要涉及访问日志(access log)和错误日志(error log)。下面从配置文件位置、基本配置、常见参数、按站点/按级别划分、日志切割几个方面说明。


一、Nginx 日志配置文件位置(Debian)

Debian 下 Nginx 常见路径:

  • 主配置文件:/etc/nginx/nginx.conf
  • 站点配置:/etc/nginx/sites-enabled/
  • 日志默认目录:/var/log/nginx/

默认日志文件:

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

二、基本日志配置

1. 错误日志(error_log)

语法:

error_log 路径 级别;

示例(在 nginx.conf 或 http {} 中):

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

日志级别(从低到高):

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

生产环境一般使用 warn 或 error


2. 访问日志(access_log)

语法:

access_log 路径 [日志格式];

示例:

access_log /var/log/nginx/access.log main;

三、自定义日志格式(log_format)

在 http {} 块中定义(通常在 nginx.conf):

log_format main '$remote_addr - $remote_user [$time_local] '
                '"$request" $status $body_bytes_sent '
                '"$http_referer" "$http_user_agent"';

常用变量说明:

  • $remote_addr:客户端 IP
  • $time_local:本地时间
  • $request:请求行
  • $status:HTTP 状态码
  • $body_bytes_sent:发送字节数
  • $http_user_agent:浏览器信息

四、为不同站点配置不同日志

在站点配置中(/etc/nginx/sites-enabled/example.conf):

server {
    listen 80;
    server_name example.com;

    access_log /var/log/nginx/example.access.log main;
    error_log  /var/log/nginx/example.error.log warn;

    location / {
        root /var/www/example;
        index index.html;
    }
}

五、关闭某类日志(不推荐长期使用)

access_log off;
error_log off;

⚠️ error_log off 实际上仍会写日志,建议用 /dev/null

error_log /dev/null;

六、日志切割(非常重要)

Debian 默认使用 logrotate

配置文件:

/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
}

手动测试:

logrotate -d /etc/logrotate.d/nginx   # 调试
logrotate -f /etc/logrotate.d/nginx  # 强制执行

七、常用排查命令

# 实时查看访问日志
tail -f /var/log/nginx/access.log

# 查看错误日志
tail -f /var/log/nginx/error.log

# 统计 404 数量
grep " 404 " /var/log/nginx/access.log | wc -l

如果你有具体需求(比如:JSON 日志、按天拆分、Docker 环境、HTTPS 站点),可以告诉我,我可以给你更针对性的配置。

0 踩