如何基于上下文根用ingress-nginx配置反向代理访问单个Pod
解决方案
要实现通过/{{pod_number}}/webgui访问对应Pod的WebUI并保持上下文根,需调整Ingress的路径匹配、重写规则,同时处理后端的跳转和链接生成问题,以下是修改后的配置模板及说明:
修改后的Ingress模板
apiVersion: v1 kind: ConfigMap metadata: name: dp-custom-ingress-manager-templates namespace: utils data: ingress-template.yaml: | apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: dp-admin-{{pod_number}} namespace: dp annotations: nginx.ingress.kubernetes.io/backend-protocol: HTTPS nginx.ingress.kubernetes.io/use-regex: "true" # 重写路径:将/{{pod_number}}/webui/xxx 转为 /xxx 发送给后端 nginx.ingress.kubernetes.io/rewrite-target: /$2 # 告诉后端应用它被代理的前缀路径,部分应用会据此生成正确的链接 nginx.ingress.kubernetes.io/proxy-set-header: "X-Forwarded-Prefix /{{pod_number}}/webui" # 修改后端返回的跳转Location,自动添加前缀 nginx.ingress.kubernetes.io/configuration-snippet: | if ($sent_http_location ~* ^(/.*)$) { set $new_location /{{pod_number}}/webui$1; proxy_set_header Location $new_location; } spec: ingressClassName: nginx tls: - hosts: - dp.pod.com secretName: dp-endpoint rules: - host: dp.pod.com http: paths: # 匹配 /{{pod_number}}/webui 和 /{{pod_number}}/webui/xxx 两种路径 - path: /({{pod_number}}/webui)(/|$)(.*) pathType: ImplementationSpecific backend: service: name: dp-custom-{{pod_number}} port: number: 9090 # SOMA端口的配置逻辑同理 - path: /({{pod_number}}/soma)(/|$)(.*) pathType: ImplementationSpecific backend: service: name: dp-custom-{{pod_number}} port: number: 5550
关键配置说明
- 路径正则调整:使用
/({{pod_number}}/webui)(/|$)(.*)同时匹配根前缀(如/2/webui)和带后缀的路径(如/2/webui/login.html),避免访问根前缀时出现404。 - 重写规则修正:
rewrite-target: /$2将匹配到的后缀部分(如login.html)直接转发给后端的8080端口,符合后端默认的上下文根要求。 - X-Forwarded-Prefix设置:传递代理前缀给后端应用,若应用支持该头部,会自动在生成的页面链接中带上
/2/webui前缀,避免页面内链接跳转出错。 - 跳转Location修正:通过
configuration-snippet拦截后端返回的跳转响应(如跳转到/login.html),自动添加前缀转为/2/webui/login.html,保证浏览器地址栏显示正确路径。
额外注意事项
- 若页面内的静态资源链接(如CSS、JS)仍不带前缀,需添加
sub_filter配置到configuration-snippet中,替换页面内的相对路径:sub_filter '<a href="/' '<a href="/{{pod_number}}/webui/'; sub_filter '<link href="/' '<link href="/{{pod_number}}/webui/'; sub_filter '<script src="/' '<script src="/{{pod_number}}/webui/'; sub_filter_once off; - 确保
pathType设置为ImplementationSpecific,因为正则匹配的路径不适合用Prefix类型。
内容的提问来源于stack exchange,提问作者dxniel7402
相关产品推荐
相关产品推荐

