Nginx 中的 React 路由

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

我正在构建一个 docker 镜像,但反应路由不起作用。当我单击 /about 路由时,它给出 404 Not Found in nginx/1.27.1 错误。它与 npm start 配合得很好。我正在使用 React Router V6。

这是我的 docker 文件:

FROM node:lts-alpine as builder

WORKDIR /app
COPY package.json .

RUN npm install
COPY . .
RUN npm run build

FROM nginx:alpine

#COPY ./.nginx/nginx.conf /etc/nginx/nginx.conf

COPY --from=builder /app/build /usr/share/nginx/html

EXPOSE 80
EXPOSE 443

ENTRYPOINT ["nginx", "-g", "daemon off;"]


这是我的 nginx.conf 文件:

# nginx.conf
user  nginx;
worker_processes  auto;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
events {
  worker_connections  1024;
}
http {
  include       /etc/nginx/mime.types;
  default_type  application/octet-stream;
  log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
  '$status $body_bytes_sent "$http_referer" '
  '"$http_user_agent" "$http_x_forwarded_for"';
  access_log  /var/log/nginx/access.log  main;
  sendfile        on;
  #tcp_nopush     on;
  
  keepalive_timeout  65;
  #gzip  on;
  #include /etc/nginx/conf.d/*.conf;
server {
  listen 80;

  location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
    try_files $uri $uri/ /index.html;
  }  
  add_header 'Access-Control-Allow-Origin' '*';
  add_header 'Access-Control-Allow-Headers' '*';
}
}

这是我的反应路由:

  return (
    <div>
      <NavigationBar/>
      <Routes>
        <Route path="/" element={<Hero />} />
        <Route path="/about" element={<About />} />
        <Route path="/services" element={<Services />} />
        <Route path="/team" element={<Team />} />
        </Routes>
    </div>
  );

如何使路由正常工作?谢谢

我希望解决 React 路由错误。谢谢

nginx react-router
1个回答
0
投票

我已经成功解决了。

COPY nginx.conf /etc/nginx/nginx.conf
© www.soinside.com 2019 - 2024. All rights reserved.