温馨提示×

怎样开启nginx访问日志功能

小樊
38
2026-09-10 07:17:11
栏目: 编程语言

开启 Nginx 访问日志(access log) 通常只需在配置中启用 access_log 指令即可。下面按常见使用场景说明。


一、确认 Nginx 是否支持访问日志

一般官方版本和大多数发行版都默认支持,无需额外模块。


二、在 Nginx 配置中开启访问日志

1️⃣ 主配置文件(常用方式)

编辑 Nginx 主配置文件,例如:

vim /etc/nginx/nginx.conf

http 块中(全局生效):

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

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

✅ 这样 所有 server 都会记录访问日志。


2️⃣ 在单个站点中开启(推荐)

编辑站点配置,例如:

vim /etc/nginx/conf.d/example.conf
server {
    listen 80;
    server_name example.com;

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

    location / {
        root /usr/share/nginx/html;
        index index.html;
    }
}

3️⃣ 关闭某个 location 的访问日志(可选)

location /health {
    access_log off;
}

三、检查并重新加载 Nginx

nginx -t
systemctl reload nginx

或:

nginx -s reload

四、查看访问日志

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

五、常见问题

❓ 日志不生成?

  • 确认路径存在且有写权限
  • 确认没有 access_log off;
  • 确认请求确实到达了对应 server

❓ 想按日期切割日志?

  • 使用 logrotate(Nginx 默认已配置)
  • 或自定义脚本 + nginx -s reopen

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

  • 你的 Nginx 安装方式(源码 / apt / yum)
  • 是否使用 Docker
  • 是否想 按虚拟主机分别记录日志

我可以直接给你一份可用配置。

0