Nginx server块中配置访问日志需用access_log指令,支持指定路径、格式(如combined或自定义main)、条件记录(via map)、多文件输出及分离错误日志。

在 Nginx 的 server 块中配置访问日志,核心是使用 access_log 指令,指定日志文件路径和可选的日志格式。
基础写法:启用默认访问日志
最简配置只需一行,Nginx 会使用内置的 combined 格式(包含 IP、时间、请求行、状态码、大小等):
access_log /var/log/nginx/example.com.access.log;
指定自定义日志格式
先在 http 块(或更外层)定义格式,再在 server 块中引用:
# 在 http 块中定义(全局生效)
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
<h1>在 server 块中使用</h1><p>access_log /var/log/nginx/example.com.access.log main;按条件记录日志(如排除健康检查)
用 map 指令标记不记录的请求,再传给 access_log 的第三个参数:
# 在 http 块中
map $request_uri $loggable {
~*^/healthz 0;
default 1;
}
<h1>在 server 块中</h1><p>access_log /var/log/nginx/example.com.access.log main if=$loggable;多日志文件或分离错误日志
可以为同一 server 同时配置多个 access_log,比如按状态码拆分,或单独记录 POST 请求:
- 记录所有请求到主日志:
access_log /var/log/nginx/access.log; - 只记录 4xx/5xx 错误到单独文件:
access_log /var/log/nginx/error_requests.log main if=$status_4xx_5xx;(需配合 map 定义变量) - 错误日志始终独立配置:
error_log /var/log/nginx/example.com.error.log warn;(注意这是error_log,不是access_log)


















