文章目录
- 方法一:使用Nginx原生配置记录访问信息
- 方法二:使用Nginx_headers_more模块记录更加详细的信息
Nginx被广泛应用于各种场景如:Web服务器、反向代理服务器、负载均衡器、Web应用防火墙(WAF)等
在实际的产品开发中,无论是功能测试或访问行为审计,都需要详细记录每一次访问行为
方法一:使用Nginx原生配置记录访问信息
vi /usr/local/nginx/conf/nginx.conf
http {
log_format detailed '[$time_local] '
'客户端IP: $remote_addr '
'请求方法: $request_method '
'URL: $request_uri '
'协议: $server_protocol '
'状态码: $status '
'响应大小: $body_bytes_sent '
'引用页: $http_referer '
'用户代理: $http_user_agent '
'请求头: "$http_headers" '
'响应头: "$sent_http_headers"';
access_log /var/log/nginx/detailed_access.log detailed;
}
测试可以发现,Nginx的访问日志中详细记录了客户端IP、请求方法、URL、HTTP版本、状态码、响应大小、referer字段、客户端浏览器等详细信息:
方法二:使用Nginx_headers_more模块记录更加详细的信息
# 1. 下载Nginx_headers_more模块源码
wget https://github.com/openresty/headers-more-nginx-module/archive/refs/heads/master.zip
unzip master.zip
# 2. 重新编译Nginx
./configure --add-module=/path/to/headers-more-nginx-module-master
make
make install
# 3. 配置Nginx记录完整访问信息
http {
more_set_input_headers 'Request-Headers: $http_headers';
more_set_headers 'Response-Headers: $sent_http_headers';
log_format detailed '[$time_local] '
'客户端IP: $remote_addr '
'请求方法: $request_method '
'URL: $request_uri '
'协议: $server_protocol '
'状态码: $status '
'响应大小: $body_bytes_sent '
'引用页: $http_referer '
'用户代理: $http_user_agent '
'完整请求头: "$more_input_headers_request_headers" '
'完整响应头: "$sent_http_response_headers"';
access_log /var/log/nginx/detailed_access.log detailed;
如果需要详细,可以使用lua脚本直接读取原始请求头和打印响应头