Nginx Not Returning CSS/JS for Subpaths: Solutions

kubernetesnginx

I have a website behind and ingress controller on k8s. This configuration was working in returning static html / css / json:

Ingress.yaml

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: example-com
  annotations:
    kubernetes.io/tls-acme: "true"
    cert-manager.io/cluster-issuer: letsencrypt-prod
    kubernetes.io/ingress.class: kong
spec:
  tls:
  - secretName: example-com
    hosts:
    - example.com
  rules:
  - host: example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: cvsite
            port: 
              number: 80

Nginx.conf

server {
    listen       80;
    server_name  example.com/blog;
    ssl_certificate     /etc/nginx/certs/tls.crt;
    ssl_certificate_key /etc/nginx/certs/tls.key;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers         HIGH:!aNULL:!MD5;
    include /etc/nginx/mime.types;
    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

However adding these 3 lines break everything:

Ingress.yaml

paths:
      - path: /cv      ##CHANGE HERE
        pathType: Prefix
        backend:
          service:
            name: cvsite
            port: 
              number: 80

Nginx.conf

location /cv {                                    #CHANGE HERE
        alias   /usr/share/nginx/html/;            #CHANGE HERE   
        index  index.html index.htm;              
    }

curl -v https://example.com/cv

*  SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x7fa82200a400)
> GET /cv HTTP/2
> Host: example.com
> User-Agent: curl/7.64.1
> Accept: */*
* Connection state changed (MAX_CONCURRENT_STREAMS == 128)!
< HTTP/2 404
< content-type: text/html; charset=UTF-8
< content-length: 153
< server: nginx/1.19.6
< date: Mon, 08 Feb 2021 17:40:19 GMT
< x-kong-upstream-latency: 1.9999771118164
< x-kong-proxy-latency: 1
< via: kong/2.2.1
<
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.19.6</center>
</body>
</html>

in Browser, https://example.com/cv returns only blank page.

How come does it return a 404, when ls /usr/share/nginx/html displays index.html and static files please ?

Best Answer

So as @mdaniel advised, moving from alias to root instead, plus fixing the path in my frontend application fixed the overall problem. This helped in case you stumble upon this thread: https://stackoverflow.com/questions/53207059/react-nginx-routing-to-subdirectory