Static website throwing 404 under Kubernetes through Ingress with prefix path

9/16/2021

I have a frontend app that is a static website. Inside this website, there are multiple references of static content (such as images or js files), and if I run a local server, I can browse it without any problem.

I wanted to deploy my site as a Kubernetes service as I have my own cluster, so I created the deployment and service, which are both running great, and then I created an ingress so I could get my site exposed through my nginx controller, and finally set the prefix path /myApp. So far so good, I can reach the site through /myApp/index.html as supposed, but each static file referenced inside this index file throws me a 404 error.

This is actually the expected behavior, because my site is reachable under this prefix path, and my content would be accessible if they were referenced with the same path. Even if I redeploy my site updating every reference appending the prefix before the rest of the path, the site works as expected (or if I point my ingress to the root path as well).

The problem here is that ideally, I would like the site running under any prefixed path without the need of manually updating every html file with the new paths.

So, according to the best practices possible, is there any way I can achieve this? Can I somehow deploy my app and assign it any random prefix path in my ingress, and at the same time have my internal references point to the correct path?

-- Luciano Marti
kubernetes
kubernetes-ingress
nginx
nginx-ingress

1 Answer

9/16/2021

You can create the Nginx ingress to append the prefix

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: test-ingres
  annotations:
    ingress.kubernetes.io/rewrite-target: /api
    kubernetes.io/ingress.class: "nginx"
spec:
  rules:
  - http:
      paths:
      - path: /auth/api
        backend:
          serviceName: service
          servicePort: 80

above ingress will rewrite path like

curl https://example.com/auth/api/ 
path: /api/

curl https://example.com/auth/api/any/whatever
path: /api/blah/whatever

instead of /auth/api you can also use the /myApp change it as per requirement.

-- Harsh Manvar
Source: StackOverflow