「Nginx」- 记录 HTTP 请求头到日志 @20210130

问题描述

我们希望在日志中记录 HTTP 请求头信息,以查看请求信息、进行请求调试等等。

该笔记将记录:在 Nginx 中,如何在日志中记录 HTTP 请求头信息。

解决方案

简单说:目前(01/11/2021),没有直接的方案(变量),需要变通处理。

方案一、枚举变量

我们自定义日志格式,并在日志中打印这些变量。如下示例,输出部分与客户端网络地址有关的变量:

log_format client_ip_address '[$time_local] Host="$http_host", '
                             'Forwarded="$http_forwarded", '
                             'X-Forwarded-For="$http_x_forwarded_for", '
                             'X-Forwarded-Host="$http_x_forwarded_host", '
                             'X-Forwarded-Proto="$http_x_forwarded_proto", '
                             'X-REAL-IP="$http_x_real_ip", '
                             'realip_remote_addr="$realip_remote_addr", '
                             'remote_addr="$remote_addr", '
                             'server_addr="$server_addr", '                          
                             'upstream_addr="$upstream_addr", ' ;

server {
	...
    access_log /var/log/nginx/client-ip-address.log client_ip_address;
    ...
}

方案二、使用 Lua 模块

1)安装 lua-nginx-module 模块:

# Debian GNU/Linux 10 (buster)
apt-get install libnginx-mod-http-lua

# 通常开箱即用,无需使用 load_module /path/to/module.so 引入模块

2)使用如下代码进行头部记录:

# 该示例,将头部信息写入日志
header_filter_by_lua_block {
  local h = ngx.req.get_headers()
  for k, v in pairs(h) do
    ngx.log(ngx.ERR, "Got header "..k..": "..v..";")
  end
}

# 该示例,将直接返回请求头
location /request_headers {
	
	default_type 'text/plain';
	
	# 或者写在变量中,然后进行引用
	set_by_lua $request_headers '
	  local h = ngx.req.get_headers()
	  local request_headers_all = ""
	  for k, v in pairs(h) do
		request_headers_all = request_headers_all .. ""..k..": "..v..";\\n"
	  end
	  return request_headers_all';
	  
	return 200 $request_headers;
	
}

注意事项,我们没有展开深入说明,只提供思路(并验证有效)。

参考文献

WikiNotes/记录 HTTP 请求头到日志
logging - How to log all headers in nginx? - Stack Overflow
openresty/lua-nginx-module: Embed the Power of Lua into NGINX HTTP servers


posted @ 2021-01-30 16:34  研究林纳斯写的  阅读(2468)  评论(0编辑  收藏  举报