Search code examples
angularkuberneteskubernetes-ingressnginx-ingress

Can we change the URL route in between ingress and service?


I have a docker image which hosts it's server on / (home) now, in ingress I already have a service(homepage) which belongs to /

What I want:

  1. going to / should take me to the home page
  2. going to /custom should take me to the docker service pointing to the image

but the problem is that since, the image is hosted on / it doesn't work on /custom. Ingress forwards it to the service but service doesn't recogize /custom, so I get NotFound and I don't have control over the image hosting path.

Is there any way around? someway I could add /custom in ingress but remove it after the service is called or something else.

CODE:

metadata:
  name: ingress-srv
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/use-regex: "true"
    nginx.ingress.kubernetes.io/proxy-body-size: 20m
    # Below is to counter gateway timeout issue.
    nginx.org/proxy-connect-timeout: 3600s
    nginx.org/proxy-read-timeout: 3600s
    nginx.org/proxy-send-timeout: 3600s
spec:
  rules:
     - host: www.mysite.com  
          http:
            paths:
              - path: /custom
                pathType: Prefix
                backend:
                  service:
                    name: image-service
                    port:
                      number: 80 
              - path: / 
                pathType: Prefix
                backend:
                  service:
                    name: frontend-service
                    port:
                      number: 80

image-service will only work if the URL is /

EDIT: Tried rewrite with ingress It works almost as I need it except for one issue, I only see the favicon(so i know the service is working) but the page is not loaded(404 resource error on console) of my angular app (hash location strategy) It also doesn't work with react (same issue) What am I missing?


Solution

  • Yes, This can be done using nginx rewrite example.
    Adding:
    nginx.ingress.kubernetes.io/rewrite-target: /$1 to annotations

    There are two things to note here:

    1. $1,$2 represents a capture group, basically it means that the content that matches the group will be rewritten.
      eg: /custom(/|$)(.*)
      (/|$) covers custom/ or custom [GROUP1 $1]
      (.*) means everything after custom/ or custom [GROUP2 $2]

    Now, If I choose $2, then /custom/xyz will become /xyz FOR THE SERVICE as only /xyz will belong to group two

    Play with regex

    1. For some reason, once I added rewrite, basic / path stopped working which I modified to /(.*) for $1 rewrite

    If you are using $2, /()(.*) should work.