Nginx 配置问题 - 带有尾部斜杠或查询参数的 React 应用程序出现空白页面和 MIME 类型错误

问题描述 投票:0回答:1

在使用 Docker 容器提供我的 vite React 应用程序时,我遇到了 Nginx 配置问题。该应用程序对于没有尾部斜杠或查询参数的 URL 运行良好,但是当添加尾部斜杠或包含查询参数时,浏览器控制台中会显示空白页面,并显示以下错误:

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 如何处理 URL 路径有关。例如,像 http://localhost/checkout/ 或 http://localhost/checkout/?canceled=true 这样的 URL 会导致 Nginx 在错误的目录中查找资产,从而导致 MIME 类型错误。但 http://localhost/checkout 工作正常并正确显示页面。 在为我的 React 应用程序提供服务时,如何配置 Nginx 来正确处理带有斜杠和查询参数的 URL?任何见解或建议将不胜感激!

我的Nginx配置如下:

upstream api {
    server backend:8000;
}

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

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

    location /api/ {
        proxy_pass http://api;
        proxy_set_header Host $http_host;
    }
}

我的 docker-compose.yml 文件:

version: "3.8"

services:
  backend:
    build:
      context: ./backend
    command: gunicorn api.wsgi --bind 0.0.0.0:8000 --workers 4
  frontend:
    build:
      context: ./client
    volumes:
      - client_build:/react/dist
  nginx:
    image: nginx:latest
    ports:
      - 80:80
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro
      - client_build:/etc/nginx/html/
    depends_on:
      - backend
      - frontend
volumes:
  client_build:
reactjs docker nginx react-router nginx-reverse-proxy
1个回答
0
投票

从日志来看,问题似乎是每当末尾添加斜杠时,nginx 就会查找相对于 url 路径的资产/静态文件。例如,如果 url 是 http://localhost/checkout/,nginx 会在 /etc/nginx/html/checkout/assets/ 文件夹而不是 /etc/nginx/html/assets/ 中查找 css 和 js 文件。

不知道为什么当没有尾部斜杠时不会发生这种情况,但在服务器块中添加它为我解决了这个问题:

location ~ ^/.*/assets/(.*) {
    alias /etc/nginx/html/assets/$1;
}

这会强制 nginx 直接在资产文件夹中查找文件。

© www.soinside.com 2019 - 2024. All rights reserved.