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
修改说明
调整/momo-store的匹配规则:
将原Prefix类型改为正则匹配/momo-store(/.*)?,确保覆盖/momo-store本身及其所有子路径(如/momo-store/cart),同时设置pathType: ImplementationSpecific以适配正则模式。修正backend路径的正则表达式:
- 第一种方案中,
^/(products|categories|orders|auth/whoami)(/.*)?$锚定路径开头,可匹配指定路径及其所有子路径; - 第二种方案使用负向预查
^/(?!momo-store)(.*)$,自动匹配所有不以/momo-store开头的请求,无需逐个列出路径。
- 第一种方案中,
验证配置生效:
应用配置后,可通过以下命令检查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
相关产品推荐
相关产品推荐

