略微加速

略速 - 互联网笔记

nginx日志记录host头 nginx日志自定义格式

2026-01-06 leiting (19阅读)

标签 运维 nginx

Nginx 的访问日志(access log)默认情况下不直接记录 HTTP 请求头中的 Host 字段,但可以通过自定义日志格式来显式记录它。


1. 默认日志格式

Nginx 默认的 combined 日志格式如下:

log_format combined '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent"';

这个格式中没有包含 $http_host(即请求头中的 Host 字段)。


2. 如何记录 Host 头?

你可以通过在 log_format 中添加 $http_host 变量来自定义日志格式。例如:

log_format custom '$remote_addr - $remote_user [$time_local] '
                  '"$request" $status $body_bytes_sent '
                  '"$http_referer" "$http_user_agent" '
                  '"$http_host"';

然后在 server 或 http 块中使用这个格式:

access_log /var/log/nginx/access.log custom;

这样,每条日志的最后一部分就会包含客户端发送的 Host 请求头。

注意:$http_host 对应的是请求头中的 Host 字段;而 $host 是 Nginx 内部解析后的主机名(优先取 Host 头,如果没有则从 Server 块的 server_name 推断),通常建议用 $http_host 来准确记录原始请求头。


3. 验证是否生效

修改配置后重载 Nginx:

nginx -t && nginx -s reload

然后访问你的服务,查看日志是否包含 Host 信息,例如:

192.168.1.100 - - [06/Jan/2026:12:00:00 +0800] "GET / HTTP/1.1" 200 612 "-" "curl/7.68.0" "example.com"

最后的 "example.com" 就是 Host 头。



北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3