Home > Software engineering >  Dockerized NGINX returns 404 instead of static React files
Dockerized NGINX returns 404 instead of static React files

Time:09-28

enter image description here

I use Docker and NGINX to serve SPA built with React. Everything was fine until I added some caching inspired by this gist. Currently, NGINX returns 404 for all files in static folder.

This is how NGINX config looks like:

server {
  listen 80;

  location / {
    root /usr/share/nginx/html/;
    include /etc/nginx/mime.types;
    try_files $uri $uri/ /index.html;
  }

  # These two location directives cause the issue, if remove them it will be running fine

  location ~* \.(?:jpg|jpeg|gif|png|ico|svg)$ {
    expires 7d;
    add_header Cache-Control "public";
  }

  location ~* \.(?:css|js)$ {
    add_header Cache-Control "no-cache, public, must-revalidate, proxy-revalidate";
  }
}

This is what error messages look like, there is etc folder prepended to the path which is invalid:

2022/09/28 09:58:46 [error] 11#11: *4 open() "/etc/nginx/html/static/css/main.45f86988.css" failed (2: No such file or directory), client: 172.17.0.1, server: , request: "GET /static/css/main.45f86988.css HTTP/1.1", host: "localhost:3244", referrer: "http://localhost:3244/"

Files are definitely stored within the container, but again without that etc folder:

/usr/share/nginx/html/static # find
.
./css
./css/main.45f86988.css
./css/main.45f86988.css.map
./js
./js/496.a53b338e.chunk.js
./js/NotFoundComponent.af4d0ff3.chunk.js
./js/main.adbec619.js
./js/main.adbec619.js.map
./js/285.f49f8f0e.chunk.js
./js/MapComponent.3d89394e.chunk.js
./js/MapComponent.3d89394e.chunk.js.map
./js/NotFoundComponent.af4d0ff3.chunk.js.map
./js/DemoContainer.7bc357cb.chunk.js.map
./js/496.a53b338e.chunk.js.map
./js/main.adbec619.js.LICENSE.txt
./js/285.f49f8f0e.chunk.js.map
./js/DemoContainer.7bc357cb.chunk.js
/usr/share/nginx/html/static #

P.S. I haven't used NGINX before and I'm sorry if the answer is obvious

CodePudding user response:

It looks like your files are in /usr/share/nginx/html/static folder, but nginx is trying to read them from /etc/nginx/html/. I would recommend moving the root /usr/share/nginx/html/ line to the server block.

Something like that:

server {
  listen 80;
  root /usr/share/nginx/html/;
 ...
 }
  • Related