traefik ingress同样可以配置URL的重写:

  • traefik 1.x配置方法

下面是一个完整例子:

 apiVersion: extensions/v1beta1
  kind: Ingress
  metadata:
    annotations:
      kubernetes.io/ingress.class: traefik
      traefik.ingress.kubernetes.io/request-modifier: 'ReplacePathRegex: ^/api3/(.*)
        /api/$1'
    creationTimestamp: "2020-03-09T03:27:40Z"
    generation: 2
    labels:
      app: public-fe-zhan-operation-node-qa
    name: public-fe-zhan-operation-node-qa-7091-2-ingress
    namespace: public-fe-node-qa
    resourceVersion: "2310342"
    selfLink: /apis/extensions/v1beta1/namespaces/public-fe-node-qa/ingresses/public-fe-zhan-operation-node-qa-7091-2-ingress
    uid: ee6f6696-61b5-11ea-a82f-52540088db9a
  spec:
    rules:
    - host: www.xxxx.com
      http:
        paths:
        - backend:
            serviceName: public-fe-zhan-operation-node-qa
            servicePort: 7091
          path: /api3

参考文档: https://s0docs0traefik0io.icopy.site/v1.7/basics/#path-matcher-usage-guidelines

https://docs.traefik.io/v1.7/basics/#rules-order

主要是配置是下面2行,使用了正则替换重写,将/api3改写为/api:

      kubernetes.io/ingress.class: traefik
      traefik.ingress.kubernetes.io/request-modifier: 'ReplacePathRegex: ^/api3/(.*)
        /api/$1'
  • traefik 2.x配置方法
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: test-replacepathregex
spec:
  replacePathRegex:
    regex: ^/foo/(.*)
    replacement: /bar/$1

traefik 2.x功能更为强大,比如下面的例子:

apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: public-arch-ep-api-v1-tomcat-dev-ingress-route
  namespace: public-arch-tomcat-dev
spec:
  entryPoints:
    - web
  routes:
    - match: Host(`www.xxx.com`) && Headers(`grayscale_rules_label`, `test_label`)
      kind: Rule
      services:
        - name: public-arch-ep-api-v1-tomcat-dev
          port: 8080
    - match: Host(`www.xxx.com`)
      kind: Rule
      services:
        - name: public-arch-ep-api-tomcat-dev
          port: 8080

访问的域名为www.xxx.com时,如果带有http header grayscale_rules_label,并且值为test_label时,访问:public-arch-ep-api-v1-tomcat-dev,否则访问到:public-arch-ep-api-tomcat-dev

参考文档:https://docs.traefik.io/middlewares/replacepathregex/