Search code examples
kuberneteskubernetes-ingress

Kubernetes Ingress backend subpath


Is it possible in any way to redirect a hostpath to a subpath on the backend? Similar how subPaths work for volumes.

The ingress would look like this:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: jupyter-notebook-ingress
  annotations:
    kubernetes.io/ingress.class: nginx
spec:
  rules:
    - host: jptrntbk.MYDOMAIN.com
      http:
        paths:
          - path: /
            backend:
              serviceName: jupyter-notebook-service
              servicePort: 8888
              subPath: /lab

Navigation to jptrntbk.MYDOMAIN.com would redirect to /lab on the backend and all other parentpaths are unavailable.


Solution

  • Create an Ingress rule with a app-root annotation:

    apiVersion: extensions/v1beta1
    kind: Ingress
    metadata:
      annotations:
        nginx.ingress.kubernetes.io/app-root: /app1
      name: approot
      namespace: default
    spec:
      rules:
      - host: approot.bar.com
        http:
          paths:
          - backend:
              serviceName: http-svc
              servicePort: 80
            path: /
    

    Check the rewrite is working

    $ curl -I -k http://approot.bar.com/
    HTTP/1.1 302 Moved Temporarily
    Server: nginx/1.11.10
    Date: Mon, 13 Mar 2017 14:57:15 GMT
    Content-Type: text/html
    Content-Length: 162
    Location: http://approot.bar.com/app1
    Connection: keep-alive
    

    or can you create an Ingress rule with a rewrite annotation:

    apiVersion: extensions/v1beta1
    kind: Ingress
    metadata:
      annotations:
        nginx.ingress.kubernetes.io/rewrite-target: /$2
      name: rewrite
      namespace: default
    spec:
      rules:
      - host: rewrite.bar.com
        http:
          paths:
          - backend:
              serviceName: http-svc
              servicePort: 80
            path: /something(/|$)(.*)
    

    In this ingress definition, any characters captured by (.*) will be assigned to the placeholder $2, which is then used as a parameter in the rewrite-target annotation.

    For example, the ingress definition above will result in the following rewrites: - rewrite.bar.com/something rewrites to rewrite.bar.com/ - rewrite.bar.com/something/ rewrites to rewrite.bar.com/ - rewrite.bar.com/something/new rewrites to rewrite.bar.com/new

    Source: https://kubernetes.github.io/ingress-nginx/examples/rewrite/