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

Nginx Ingress正则多路径配置失效,非/momo-store请求报404

问题分析与解决方案

当前Ingress配置的核心问题在于正则路径写法不完整,导致仅能匹配精确路径(如/orders),无法匹配子路径(如/orders/123),同时正则未正确锚定开头,可能引发匹配逻辑异常。此外,/momo-store的Prefix类型在启用正则注解后,可能与正则路径的匹配优先级产生冲突。

修正后的Ingress配置

如果仅需转发指定的几个路径(/products、/categories、/orders、/auth/whoami)到backend:

---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: {{ .Chart.Name }}
  annotations:
    nginx.ingress.kubernetes.io/use-regex: "true"
spec:
  ingressClassName: "nginx"
  rules:
  - host: "{{ .Values.fqdn }}"
    http:
      paths:
      - path: /momo-store(/.*)?
        pathType: ImplementationSpecific
        backend:
          service:
            name: frontend
            port:
              number: 8080
      - path: ^/(products|categories|orders|auth/whoami)(/.*)?$
        pathType: ImplementationSpecific
        backend:
          service:
            name: backend
            port:
              number: 8081

如果需要将所有非/momo-store路径都转发到backend(更贴合你“其余请求”的描述):

---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: {{ .Chart.Name }}
  annotations:
    nginx.ingress.kubernetes.io/use-regex: "true"
spec:
  ingressClassName: "nginx"
  rules:
  - host: "{{ .Values.fqdn }}"
    http:
      paths:
      - path: /momo-store(/.*)?
        pathType: ImplementationSpecific
        backend:
          service:
            name: frontend
            port:
              number: 8080
      - path: ^/(?!momo-store)(.*)$
        pathType: ImplementationSpecific
        backend:
          service:
            name: backend
            port:
              number: 8081

修改说明

  1. 调整/momo-store的匹配规则:
    将原Prefix类型改为正则匹配/momo-store(/.*)?,确保覆盖/momo-store本身及其所有子路径(如/momo-store/cart),同时设置pathType: ImplementationSpecific以适配正则模式。

  2. 修正backend路径的正则表达式:

    • 第一种方案中,^/(products|categories|orders|auth/whoami)(/.*)?$锚定路径开头,可匹配指定路径及其所有子路径;
    • 第二种方案使用负向预查^/(?!momo-store)(.*)$,自动匹配所有不以/momo-store开头的请求,无需逐个列出路径。
  3. 验证配置生效:
    应用配置后,可通过以下命令检查nginx ingress控制器的生成规则:

    kubectl exec -it $(kubectl get pods -n kube-system -l app=nginx-ingress -o name) -- cat /etc/nginx/nginx.conf | grep -A 10 -B 5 "momo-store"
    

    同时测试不同路径的请求,确认转发逻辑正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 04:07:38