在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注解

NameDescriptionValues
nginx.ingress.kubernetes.io/rewrite-targetTarget URI where the traffic must be redirectedstring
nginx.ingress.kubernetes.io/ssl-redirectIndicates if the location section is accessible SSL only (defaults to True when Ingress contains a Certificate)bool
nginx.ingress.kubernetes.io/force-ssl-redirectForces the redirection to HTTPS even if the Ingress is not TLS Enabledbool
nginx.ingress.kubernetes.io/app-rootDefines the Application Root that the Controller must redirect if it's in '/' contextstring
nginx.ingress.kubernetes.io/use-regexIndicates if the paths defined on an Ingress use regular expressionsbool

上述脚本需要修改为:

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。

Logo

开源、云原生的融合云平台

更多推荐