Istio Ingress配置HttpRewrite后附加资源请求404问题
解决Istio路由后页面内部请求404的问题
这问题我之前在配置Istio路由时也踩过坑!咱们先理清楚问题根源:
你配置了HttpRewrite把/v1/endpoint重写成/endpoint转发给service-v1,这一步没问题。但应用返回的页面里发起的/endpoint2是绝对路径请求,浏览器会直接向/endpoint2发送请求,而Istio没有针对这个路径的路由规则,自然就返回404了——毕竟实际需要的是/v1/endpoint2才能匹配到service-v1的对应端点。
下面给你几个可行的解决方案,按推荐程度排序:
1. 修改应用页面路径(最推荐)
直接调整应用前端页面里的请求路径:
- 把绝对路径
/endpoint2改成相对路径./endpoint2:这样浏览器会基于当前页面的URL(/v1/endpoint)自动拼接成/v1/endpoint2 - 或者直接写成带前缀的绝对路径
/v1/endpoint2
这种方式最规范,因为应用本身明确知道自己在Istio路由下的前缀,从源头避免路径不匹配的问题。
2. 优化Istio VirtualService配置(无需改应用)
如果不想修改应用,可以调整VirtualService规则,让所有/v1/开头的请求都自动去掉前缀转发给service-v1:
apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: service-v1-vs spec: hosts: - "*" gateways: - 你的网关名称 # 替换成实际的Istio Gateway名称 http: - match: - uri: prefix: "/v1/" rewrite: uri: "/" # 把/v1/开头的路径前缀去掉,比如/v1/endpoint变成/endpoint,/v1/endpoint2变成/endpoint2 route: - destination: host: service-v1 port: number: 80 # 替换成service-v1的实际端口
这样不管是初始的/v1/endpoint还是后续的/v1/endpoint2,都会被正确转发到service-v1对应的端点。
3. 添加重定向规则(临时补救)
如果上面两种方式都暂时没法实施,可以给/endpoint2添加重定向规则,让浏览器自动跳转到/v1/endpoint2:
apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: service-v1-vs spec: hosts: - "*" gateways: - 你的网关名称 http: # 原有/v1/相关路由规则 - match: - uri: exact: "/v1/endpoint" rewrite: uri: "/endpoint" route: - destination: host: service-v1 port: number: 80 # 新增重定向规则 - match: - uri: exact: "/endpoint2" redirect: uri: "/v1/endpoint2"
这个方案会让浏览器收到301/302重定向后,重新发起/v1/endpoint2的请求,虽然能解决问题,但会多一次网络请求,用户体验略有影响,适合临时过渡使用。
内容的提问来源于stack exchange,提问作者Sergii Bishyr
相关产品推荐
相关产品推荐

