You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker化NGINX返回404,无法加载React静态文件问题

问题:Docker+NGINX部署React SPA添加缓存配置后静态资源404

原本运行正常的React单页应用(SPA),通过Docker和NGINX部署,添加缓存规则后,static文件夹内所有文件均返回404错误,移除新增的两个location指令后恢复正常。

当前NGINX配置

server {
  listen 80;

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

  # 这两个location指令引发问题,移除后恢复正常
  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";
  }
}

错误日志

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/"

容器内实际文件路径

/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 #

解决方案

问题出在新增的两个location块未指定root路径,NGINX会使用默认的/etc/nginx/html作为根路径,导致找不到实际存储在/usr/share/nginx/html下的静态文件。

方案1:将root配置提升到server级别(推荐)

把root指令放到server块中,让所有location块继承这个根路径:

server {
  listen 80;
  root /usr/share/nginx/html/; # 全局根路径,所有location继承
  include /etc/nginx/mime.types;

  location / {
    try_files $uri $uri/ /index.html;
  }

  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";
  }
}

方案2:在每个新增的location块中单独指定root

server {
  listen 80;

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

  location ~* \.(?:jpg|jpeg|gif|png|ico|svg)$ {
    root /usr/share/nginx/html/; # 单独指定根路径
    expires 7d;
    add_header Cache-Control "public";
  }

  location ~* \.(?:css|js)$ {
    root /usr/share/nginx/html/; # 单独指定根路径
    add_header Cache-Control "no-cache, public, must-revalidate, proxy-revalidate";
  }
}

内容的提问来源于stack exchange,提问作者Renat Zamaletdinov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 07:15:33