在k8s中使用ingress的过程中,需要创建ingress对象来为Controller制定转发规则(k8s ingress相关参考),一般yaml文件为:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: ing-nginx
annotations:
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/use-regex: "true"
nginx.ingress.kubernetes.io/enable-cors: "true"
spec:
tls:
- hosts:
- test.nginx.cn
secretName: secret-tls-ingress
rules:
- host: test.nginx.cn
http:
paths:
- backend:
serviceName: svc-nginx
servicePort: 80
path: /testNG
上述脚本,表示会将https://test.nginx.cn/testNG/URL转发到集群中的https://svc-nginx/testNG/URL上,也就是说最后一行的path: /testNG也会当作请求的一部分,追加到url中。
但是,如果nginx实际的请求地址为https://svc-nginx/test-ng/URL,则会报404,找不到服务。
因此,需要使用rewrite注解:
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 |
上述脚本需要修改为:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: ing-nginx
annotations:
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/use-regex: "true"
nginx.ingress.kubernetes.io/enable-cors: "true"
nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
tls:
- hosts:
- test.nginx.cn
secretName: secret-tls-ingress
rules:
- host: test.nginx.cn
http:
paths:
- backend:
serviceName: svc-nginx
servicePort: 80
path: /testNG(/|$)(.*)
表达式说明((/|$)(.*)):两个括号用以分组,第一个是匹配 / 或者 $表示已经结束,第二组 .表示任意一个非换行符的字符 *表示0次或多次,两部分组合到一起就是,以 /匹配任意内容的,都转发到 /第二部分匹配到的文本。
再请求https://test.nginx.cn/testNG/URL,会转发到https://test.nginx.cn/URL,path的声明由指定路径改为一个正则表达式,匹配上/testNG(/|$)(.*)的请求,都会转发到一个以“/”开始拼接正则表达式的第二个组内容的URL,使用这种方式去掉了testNG。