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

如何在K8s Ingress中提取主机通配符并映射到URL路径

实现动态子域名到指定路径的转发方案

你可以通过 ingress-nginx的变量捕获+URL重写功能 实现需求,核心是从请求的Host中提取子域名,再拼接成目标转发路径。以下是完整的可运行配置及说明:

正确的Ingress配置

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
    # 核心:用nginx正则替换提取子域名,拼接目标路径
    nginx.ingress.kubernetes.io/rewrite-target: /proxy/${regex_replace($host, '\.example\.com$', '')}/$1
  name: nginx-forward
spec:
  rules:
  - host: "*.example.com"
    http:
      paths:
      - path: /(.*)
        pathType: Prefix
        backend:
          service:
            name: service
            port:
              number: 8080
  tls:
  - hosts:
    - "*.example.com"
    secretName: my-secret

关键配置解析

  1. 通配符Host匹配:*.example.com 会匹配所有以.example.com为后缀的子域名请求(如foo.example.com、bar.example.com)。
  2. 子域名提取:
    • $host 是nginx内置变量,代表当前请求的完整主机名;
    • regex_replace($host, '\.example\.com$', '') 会通过正则去掉主机名的.example.com后缀,直接得到子域名(如foo、bar)。
  3. 路径拼接:$1 对应路径规则/(.*)捕获的原URL路径内容,比如请求foo.example.com/api/v1会被重写到/proxy/foo/api/v1。

可选:过滤根域名请求

如果需要避免根域名example.com被错误匹配,可以添加server-snippet注解做过滤:

nginx.ingress.kubernetes.io/server-snippet: |
  if ($host = "example.com") {
    return 404; # 可根据需求改为跳转或其他逻辑
  }

内容的提问来源于stack exchange,提问作者zzm

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 03:10:48