解析操作httpheaders并添加到Nginx中访问日志

Parse and manipulate http headers and add them to access log in Nginx

我想配置 nginx,以便它解析 http headers 并添加新的已解析字符串以访问日志。下面是我需要的具体场景:

传入请求中有X-Forwarded-For header 包含多个IP(客户端IP + 一些代理服务器IP)。

X-Forwarded-For = "1.2.3.4, 5.6.7.8"

这是我的 nginx 中的 log_format 配置:

log_format  main  '{"timestamp":"$time_iso8601",'
                        '"clientIp":"$http_x_forwarded_for",'
                        '"conSerial":"$connection",'
                        '"agent":"$http_user_agent"}';

我在这里想要的是解析 X-Forwarded-For header 并提取代理服务器的 IP 并以日志格式添加它,并带有单独的标记,如下所示:

log_format  main  '{"timestamp":"$time_iso8601",'
                            '"clientIp":"$http_x_forwarded_for",'
                            '"proxy": "5.6.7.8",'
                            '"conSerial":"$connection",'
                            '"agent":"$http_user_agent"}';

注意1.2.3.4是客户端真实ip,5.6.7.8是代理服务器ip。

提前致谢,如有任何帮助,我们将不胜感激。

map指令可以通过使用命名捕获构造您需要的变量。例如:

map $http_x_forwarded_for $proxy_label {
    default               "";
    "~, (?<proxy_ip>.*)$" "proxy";
}

log_format  main  '{"timestamp":"$time_iso8601",'
    '"clientIp":"$http_x_forwarded_for",'
    '"$proxy_label":"$proxy_ip",'
    '"conSerial":"$connection",'
    '"agent":"$http_user_agent"}';

当没有匹配时,你可以用 $proxy_label 做一些聪明的事情。

详情见this document

编辑:要匹配行中的最后一个 IP 地址,您只能捕获 . 和这样的数字...

"~(?<proxy_ip>[0-9.]+)$" "proxy";

看到这个有用resource for regular expressions