温馨提示×

怎样开启nginx调试日志

小樊
46
2026-09-25 13:58:53
栏目: 编程语言

在 Nginx 中开启调试日志(debug log),通常有以下几种方式,取决于你想调试的范围和 Nginx 的编译情况。


一、前提:Nginx 是否支持 debug 日志

Nginx 的 debug 日志级别 只有在编译时开启了 --with-debug 才有效。

查看是否支持 debug

nginx -V 2>&1 | grep -- '--with-debug'
  • 有输出:支持
  • 无输出:不支持(需重新编译或安装带 debug 的版本)

二、开启全局调试日志(最简单)

编辑 nginx.conf:

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

⚠️ 注意:

  • debug 会输出大量日志
  • 仅建议在测试环境使用

三、只对某个 location / server 开启 debug

server {
    listen 80;
    server_name example.com;

    error_log /var/log/nginx/example_debug.log debug;

    location / {
        # 正常配置
    }
}

或只针对某个 location:

location /api/ {
    error_log /var/log/nginx/api_debug.log debug;
}

四、调试重写规则(rewrite)

error_log /var/log/nginx/rewrite.log notice;
rewrite_log on;
  • rewrite_log on; 会输出 rewrite 过程
  • 一般配合 notice 或 debug

五、使用 debug_connection(生产环境推荐)

只调试特定 IP,避免日志爆炸:

events {
    debug_connection 192.168.1.100;
    debug_connection 10.0.0.0/8;
}

需配合:

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

✅ 适合线上排错


六、查看日志

tail -f /var/log/nginx/error.log

七、常见坑

  1. debug 日志不生效
    • 没加 --with-debug
  2. 日志太大
    • 用 debug_connection
  3. Docker / 容器
    • 确认日志挂载路径正确

八、快速示例(最小可用)

worker_processes 1;

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

events {
    worker_connections 1024;
}

http {
    server {
        listen 80;
        location / {
            return 200 "ok";
        }
    }
}

如果你愿意,可以告诉我:

  • 用的是 源码 / apt / yum / Docker
  • 想调试 反向代理 / rewrite / 性能 / SSL

我可以给你更精确的配置。

0 踩