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

Docker部署Vite React应用:Nginx尾斜杠/查询参数处理异常排查

解决Docker部署Vite React应用的Nginx路径问题

问题现象

部署Vite React应用到Docker容器后,无尾斜杠或不带查询参数的URL(如http://localhost/checkout)可正常访问,但添加尾斜杠(如http://localhost/checkout/)或查询参数(如http://localhost/checkout/?canceled=true)时,页面显示空白,浏览器控制台报错:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

错误原因

问题出在Nginx的location /配置使用了alias指令:

  • 当请求带尾斜杠的URL时,Nginx会将请求路径解析为目录(如/checkout/对应/etc/nginx/html/checkout/),尝试在该目录下查找静态资源,但Vite构建的所有资源都存放在根目录/etc/nginx/html/中,导致资源查找失败。
  • Nginx最终返回index.html作为 fallback,但浏览器会把原本应该加载的JS文件(如assets/index.xxx.js)当成HTML文件解析,触发MIME类型不匹配错误。

修复方案

修改Nginx配置

将location /中的alias替换为root,并调整路径格式:

upstream api {
    server backend:8000;
}

server {
    listen 80;
    listen [::]:80;
    server_name localhost;

    location / {
        root /etc/nginx/html;
        try_files $uri $uri/ /index.html;
    }

    location /api/ {
        proxy_pass http://api;
        proxy_set_header Host $http_host;
    }
}
  • root指令会将请求路径直接拼接在指定目录后(如/checkout对应/etc/nginx/html/checkout),若文件不存在则触发try_files规则返回index.html,完全适配单页应用的路由逻辑。
  • 注意root路径末尾不要加斜杠,避免路径拼接时出现冗余层级。

确认Vite构建配置

确保Vite项目的vite.config.js中base配置为根路径(默认值即为/),避免资源路径前缀错误:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  base: '/', // 保持根路径配置
});

验证步骤

  1. 重新构建前端应用:在前端目录执行npm run build,确保构建产物同步到client_build卷。
  2. 重启Nginx容器:执行docker-compose restart nginx加载新配置。
  3. 测试带尾斜杠和查询参数的URL,确认页面正常加载,控制台无MIME类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 21:27:12