侧边栏壁纸
  • 累计撰写 12 篇文章
  • 累计创建 10 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

nginx-ingress获取自定义header头

爱动脑的脑花
2024-07-17 / 0 评论 / 0 点赞 / 16 阅读 / 3662 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2024-07-17,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

1.先说背景

今天有一个需求大体是要向nginx-ingress发送一个请求,但不知道nginx-ingress是否会删除、保留、替换请求头。于是想要对默认的nginx-ingress日志打印进行改造。

访问的curl大体如下,敏感信息已替换:

curl --location-trusted -u xxxxxx:xxxxxxx -H "label:label1" \
    -H "Expect:100-continue" \
    -H "format:CSV" \
    -H "column_separator:#" \
    -H "timeout:100" \
    -H "columns:id,name,score" \
    -T ~/Files/example1.csv -XPUT \
    http://xxxxxxxxx/api/abc/table1/_stream_load

2.现在的配置

我们采用是来自bitnami的nginx-ingress镜像,其中关键代码配置如下:

      containers:
        - name: controller
          image: >-
            镜像源/nginx-ingress-controller:1.10.0-debian-12-r3
          args:
            - >-
              --default-backend-service=$(POD_NAMESPACE)/nginx-ingress-controller-default-backend
            - '--http-port=8080'
            - '--https-port=8443'
            - '--healthz-port=10254'
            - '--election-id=ingress-controller-leader'
            - '--controller-class=k8s.io/ingress-nginx'
            - '--configmap=$(POD_NAMESPACE)/nginx-ingress-controller'

可以看到其中nginx-ingress的configmap来自于:

--configmap=$(POD_NAMESPACE)/nginx-ingress-controller

接下来我们找到这个configmap文件,看里面都有啥。

核心代码如下:

data:
  allow-snippet-annotations: 'false'

啥都没,那我们就手动添加一下配置。

此处放一下官方文档的链接:

https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/log-format/

官方给出的配置样例如下:

但我们要的是打印出自定义请求头,继续查资料,发现了规则:


Nginx 会自动为每个请求头创建一个对应的变量,但是有一些注意事项:

  • 变量名称:Nginx 会将请求头的名称转换为小写,并将破折号(-)替换为下划线(_)。所以 "Content-Type" 会变成 $http_content_type

  • 非标准头:对于非标准的 HTTP 头(如您使用的 "columns"),Nginx 通常会创建对应的变量。

  • 变量值:即使变量被创建,它的值也可能是空的,这取决于 Nginx 的配置和处理方式。

  • 配置限制:某些 Nginx 配置可能会限制哪些自定义头可以被处理或记录。

3.修改

知道了规则以后我们对configmap进行修改。

部分代码如下:

data:
  allow-snippet-annotations: 'true'
  enable-underscores-in-headers: 'true'
  log-format-upstream: >-
    $remote_addr - $remote_user [$time_local] "$request" $status
    $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"
    - Authorization: "$http_authorization" - Label: "$http_label" - Expect:
    "$http_expect" - Format: "$http_format" - Column_Separator:
    "$http_column_separator" - Timeout: "$http_timeout" - Columns:
    "$http_columns"

成功。

0
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区