log_format必须定义在http块内且名称唯一,server块中仅可引用;access_log需显式指定格式名才生效,否则回退至默认combined格式。

在 Nginx 的 server 模块中,不能直接定义日志格式——log_format 指令只允许出现在 http 块内,这是硬性语法限制。你只能在 server 块里引用已定义好的格式。
必须在 http 块中定义 log_format
所有自定义日志格式都得写在 http { ... } 大括号内部,例如:
- 打开
nginx.conf(路径通常为/opt/nginx/conf/nginx.conf或/usr/local/nginx/conf/nginx.conf) - 找到
http {开头的位置,在其内部添加:
log_format json escape=json '{ "time":"$time_iso8601", "ip":"$http_x_forwarded_for", "method":"$request_method", "uri":"$request_uri", "status":$status, "size":$body_bytes_sent, "rt":$request_time};
在 server 块中启用该格式
定义完后,才能在某个 server 块里用 access_log 指定它:
- 确保日志路径是绝对路径(如
/var/log/nginx/myapp-access.log),避免因工作目录不确定导致写入失败 - 确认该路径所在目录存在,且运行 Nginx 的用户(如
www-data或nginx)有写权限 - 示例配置:
server { listen 80; server_name example.com; access_log /var/log/nginx/example-access.log json; # 其他配置...}
常见错误与检查点
如果日志没按预期输出,重点排查这几项:
-
log_format是否写在了server或location内?——会报错,必须挪到http层 - 格式名称(如
json)是否拼写一致?大小写敏感,且不能重复定义 -
access_log路径的父目录是否存在?执行mkdir -p /var/log/nginx并chown nginx:nginx /var/log/nginx - 改完配置后是否执行了
nginx -t验证 +nginx -s reload生效?
默认可用的格式名
Nginx 自带两个预定义格式,可直接使用,无需额外定义:
-
combined:Apache 风格,含 referer 和 UA,等价于常见 main 格式 -
main:多数发行版默认启用的格式,内容与combined基本一致
例如:access_log /var/log/nginx/access.log combined; 可直接生效。











