You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kubernetes Nginx Ingress http-snippet注解不生效问题排查求助

问题根因

  1. Nginx的map指令仅允许定义在http配置块中,nginx.ingress.kubernetes.io/configuration-snippet注入的内容属于location块范围,直接将map规则写在此处会触发语法校验失败。
  2. 第一版配置中已经在http-snippet中正确定义了提取纯IP的map规则,但最终设置请求头时没有使用提取后的$forwarded-for-ip变量,仍然使用了原始带端口的$http_x_forwarded_for,所以配置没有生效。

修复后配置

ingress:
  enabled: true
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/ssl-redirect: "false"
    nginx.ingress.kubernetes.io/use-regex: "true"
    nginx.ingress.kubernetes.io/rewrite-target: /$1
    nginx.ingress.kubernetes.io/backend-protocol: https
    nginx.ingress.kubernetes.io/http-snippet: |
      map $http_x_origin_forwarded_for $forwarded-for-ip {
        # 匹配带端口的IPv4格式,提取纯IP部分
        ~^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+):[0-9]+ $1;
        # 兼容不带端口的IPv4场景,直接返回原始值
        ~^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$ $1;
        # 匹配失败兜底用远程地址,避免传空值导致后端异常
        default $remote_addr;
      };
    nginx.ingress.kubernetes.io/configuration-snippet: |
      # 使用map提取后的纯IP变量设置请求头
      proxy_set_header X-Forwarded-For $forwarded-for-ip;

补充说明

如果实际需要处理的原始头是X-Forwarded-For而不是X-Origin-Forwarded-For,将map的源变量替换为$http_x_forwarded_for即可。


内容的提问来源于stack exchange,提问作者Bruno Justino Praciano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 19:48:03