[TOC]
可以直接在 Ingress 中配置 rewrite. 你需要在
annotation
中, 增加 nginx.org/rewrites即可。
语法如下
nginx.org/rewrites: "serviceName=service1 rewrite=rewrite1[;serviceName=service2 rewrite=rewrite2;...]"
例子
需求: 有两个uri需要进行rewrite.
访问 https://ent-pc-test.fenghong.tech/api/abc 跳转至 https://ent-pc-test.fenghong.tech/huohua-ent-admin/abc
访问 https://ent-pc-test.fenghong.tech/api/public/abc 跳转至 https://ent-pc-test.fenghong.tech/huohua-ent-api/api/abc
yaml文件如下, 注意pathType: ImplementationSpecific
是kubernetes
集群v1.18的新特性。 低版本请删除该行。
$ cat ingress.yaml
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: web-huohua-ent-pc
namespace: huohua
annotations:
k8s.kuboard.cn/displayName: huohua-ent-pc
k8s.kuboard.cn/workload: web-huohua-ent-pc
nginx.org/rewrites: "serviceName=svc-huohua-ent-api
rewrite=/huohua-ent-api/api/;serviceName=svc-huohua-ent-admin
rewrite=/huohua-ent-admin/"
spec:
rules:
- host: ent-pc-test.fenghong.tech
http:
paths:
- backend:
serviceName: web-huohua-ent-pc
servicePort: huohua-ent-pc
path: /
pathType: ImplementationSpecific ## v1.18的新特性。低版本请删除
- backend:
serviceName: svc-huohua-ent-api
servicePort: ent-api
path: /api/public/
pathType: ImplementationSpecific
- backend:
serviceName: svc-huohua-ent-admin
servicePort: ent-admin
path: /api/
pathType: ImplementationSpecific
当需要访问serviceName
为svc-huohua-ent-admin
时. rewrite
规则生效如下:
-
访问
/api/
->/huohua-ent-admin/
-
访问
/api/abc
->/huohua-ent-admin/abc
当需要访问的serviceName
为svc-huohua-ent-api
时, rewrite规则生效如下:
/api/public/
->/huohua-ent-api/api/
/api/public/abc
->/huohua-ent-api/api/abc
更新
$ kubectl apply -f ingress.yaml
$ kubectl describe ing web-huohua-ent-pc -n huohua
Name: web-huohua-ent-pc
Namespace: huohua
Address:
Default backend: default-http-backend:80 (<error: endpoints "default-http-backend" not found>)
Rules:
Host Path Backends
---- ---- --------
ent-pc-test.fenghong.tech
/ web-huohua-ent-pc:huohua-ent-pc (100.70.101.191:80)
/api/public/ svc-huohua-ent-api:ent-api (100.70.101.138:8080)
/api/ svc-huohua-ent-admin:ent-admin (100.70.101.172:8081)
Annotations: k8s.kuboard.cn/displayName: huohua-ent-pc
k8s.kuboard.cn/workload: web-huohua-ent-pc
nginx.org/rewrites: serviceName=svc-huohua-ent-api rewrite=/huohua-ent-api/api/;serviceName=svc-huohua-ent-admin rewrite=/huohua-ent-admin/
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal AddedOrUpdated 3m25s (x8 over 3d3h) nginx-ingress-controller Configuration for huohua/web-huohua-ent-pc was added or updated
Normal AddedOrUpdated 3m25s (x8 over 3d3h) nginx-ingress-controller Configuration for huohua/web-huohua-ent-pc was added or updated
Normal AddedOrUpdated 3m25s (x8 over 3d3h) nginx-ingress-controller Configuration for huohua/web-huohua-ent-pc was added or updated