Azure应用网关Ingress配置:迁移至根目录后保留原URL
解决方案
针对你的需求,核心问题在于混淆了Nginx Ingress和Azure Application Gateway Ingress的注解,同时需要配合应用侧的上下文路径配置,以下是具体步骤:
1. 修正Ingress配置(仅使用Azure App Gateway注解)
你当前使用的是azure/application-gateway的Ingress类,所以Nginx相关的注解(如nginx.ingress.kubernetes.io/server-snippet)完全无效,需要替换为Azure App Gateway支持的配置:
第一步:创建路径重写规则(RewriteRuleSet CRD)
首先定义一个重写规则,将请求路径中的/product/前缀移除后转发到后端(因为你的应用已部署为ROOT.war,后端上下文是/):
apiVersion: networking.azure.io/v1 kind: RewriteRuleSet metadata: name: product-path-rewrite namespace: product spec: rewriteRules: - name: remove-product-prefix ruleSequence: 100 conditions: - variable: Request_URI pattern: "^/product/(.*)" ignoreCase: true actionSet: urlConfiguration: modifiedPath: "/{R:1}" queryString: "{originalQueryString}" reroute: true
第二步:更新Ingress资源
配置两个路径规则:
- 对根路径
/执行永久重定向到/product,确保地址栏显示正确路径 - 对
/product/*路径使用上述重写规则,转发到后端服务
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: annotations: appgw.ingress.kubernetes.io/backend-hostname: company.com appgw.ingress.kubernetes.io/backend-protocol: https appgw.ingress.kubernetes.io/cookie-based-affinity: "true" appgw.ingress.kubernetes.io/ssl-redirect: "true" kubernetes.io/ingress.class: azure/application-gateway # 为/product路径绑定重写规则 appgw.ingress.kubernetes.io/rewrite-rule-set: product-path-rewrite # 根路径重定向配置 appgw.ingress.kubernetes.io/redirect-to: "https://company.com/product" appgw.ingress.kubernetes.io/redirect-type: "Permanent" generation: 4 labels: app.kubernetes.io/managed-by: Helm name: website-ingress namespace: product spec: rules: - host: company.com http: paths: # 根路径重定向 - path: / pathType: Exact backend: service: name: product-service port: number: 443 # product路径转发+重写 - path: /product/* pathType: Prefix backend: service: name: product-service port: number: 443 tls: - hosts: - company.com secretName: product-sslcert
2. 调整Tomcat应用上下文路径
因为你的应用现在是ROOT.war部署,默认上下文路径为/,导致应用生成的跳转链接(如登录页)不带/product前缀。需要在Tomcat启动参数中添加:
-Dserver.servlet.context-path=/product
如果是用K8s Deployment部署,可以在环境变量中设置:
env: - name: CATALINA_OPTS value: "-Dserver.servlet.context-path=/product"
这样应用自身生成的所有链接都会带上/product前缀,确保浏览器地址栏始终显示company.com/product/...的路径。
关键说明
- 必须移除所有Nginx Ingress的注解,因为你使用的是Azure Application Gateway的Ingress Controller,两者注解不兼容
- 重写规则负责将外部的
/product/xxx转换为后端的/xxx,适配ROOT.war的部署方式 - 应用侧的上下文路径配置是核心,否则应用生成的内部链接会跳回根路径,导致地址栏不符合预期
内容的提问来源于stack exchange,提问作者Chethan S.
相关产品推荐
相关产品推荐

