在 Nginx 中开启访问日志(access log)通常只需要配置 access_log 指令即可。下面分几种常见情况说明。
Nginx 默认就有访问日志,一般在:
http {
access_log /var/log/nginx/access.log;
}
如果你没改过配置,默认就是开启的。
编辑站点配置,例如:
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 /usr/share/nginx/html;
index index.html;
}
}
在 http 块中定义日志格式:
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 或 location 中使用:
access_log /var/log/nginx/access.log main;
如果某些请求不想记录(如健康检查):
location = /health {
access_log off;
}
nginx -t # 检查配置是否正确
nginx -s reload # 重新加载配置
tail -f /var/log/nginx/access.log
access_log 没有被 offreload日志通常在:
docker logs nginx
或挂载了 /var/log/nginx
如果你愿意,可以告诉我:
我可以给你一份可直接用的完整配置。