ingress rewrite 重定向
在kubetnetes使用中,需创建转发规则;
示例一:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: test-nginx
annotations:
kubernetes.io/ingress.class: "nginx"
spec:
rules:
- host: www.test.cn
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: test-admin
port:
number: 80
paths:
- path: /api
pathType: Prefix
backend:
service:
name: test-api
port:
number: 80
说明,访问http://www.test.cn/api/*内容会直接转发到svc集群中http://test-api/api/* 上,这里访问svc时会带上目录名称; 就是说 - path 的值转发给svc时也会追加到url中,在访问就会404,实际我们需要访问的地址http://test-api/*;
Name | Description | Values |
---|---|---|
nginx.ingress.kubernetes.io/rewrite-target | Target URI where the traffic must be redirected | string |
nginx.ingress.kubernetes.io/ssl-redirect | Indicates if the location section is accessible SSL only (defaults to True when Ingress contains a Certificate) | bool |
nginx.ingress.kubernetes.io/force-ssl-redirect | Forces the redirection to HTTPS even if the Ingress is not TLS Enabled | bool |
nginx.ingress.kubernetes.io/app-root | Defines the Application Root that the Controller must redirect if it's in '/' context | string |
nginx.ingress.kubernetes.io/use-regex | Indicates if the paths defined on an Ingress use regular expressions | bool |
使用rewrite-target将请求转发到http://test-api/*;参考地址:Rewrite - NGINX Ingress Controller (kubernetes.github.io)
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: test-api
annotations:
kubernetes.io/ingress.class: "nginx"
nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
rules:
- host: www.test.cn
http:
paths:
- path: /api(/|$)(.*)
pathType: Prefix
backend:
service:
name: api-svc
port:
number: 8080
按照要求我们需要在 path
中匹配前缀 api
,然后通过 rewrite-target
指定svc,表达式说明((/|$)(.*)):两个括号用以分组,第一个是匹配 / 或者 $表示已经结束,第二组 .表示任意一个非换行符的字符 *表示0次或多次,两部分组合到一起就是,以 /匹配任意内容的,都转发到 /第二部分匹配到的文本。 ‘
此时在请求www.test.cn/api 就会转发到 api-svc上;