Nginx 的访问日志(access log)默认情况下不直接记录 HTTP 请求头中的 Host 字段,但可以通过自定义日志格式来显式记录它。
Nginx 默认的 combined 日志格式如下:
log_format combined '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent"';
这个格式中没有包含 $http_host(即请求头中的 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来准确记录原始请求头。
修改配置后重载 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 头。
最新评论: