"Nginx"-Log HTTP request headers to log@20210223

Problem Description

We hope to record HTTP request header information in the log to view request information, request debugging, and so on.

This note will record: How to record HTTP request header information in the log in Nginx.

solution

Simply put: At present (01/11/2021), there is no direct solution (variable), and a workaround is needed.

Solution one, enumerated variables

We customize the log format and print these variables in the log. In the following example, some variables related to the client's network address are output:

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;
    ...
}

Solution two, use Lua module

1) Install the lua-nginx-module module:

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

# Usually used out of the box, no need to use load_module /path/to/module.so to import modules

2) Use the following code to record the header:

# In this example, write the header information to the log 
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 
} 

# This example will directly return the request header 
location /request_headers { 

	default_type'text/plain'; 

	# Or write it in a variable and then reference 
	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; 

}

Note, we did not expand the in-depth explanation, only provide ideas (and verify the validity).

related articles

"Nginx"-custom log format
"Nginx"-use variables in the log path

references

logging - How to log all headers in nginx? - Stack Overflow
openresty/lua-nginx-module: Embed the Power of Lua into NGINX HTTP servers

Guess you like

Origin blog.csdn.net/u013670453/article/details/113987188