我将react.js应用程序上传到服务器。我在使用nginx服务器。应用程序运行良好。但是当我转到另一个页面&刷新时,这个站点就不能工作了。它显示了一个404找不到的错误。
我怎么才能解决这个问题?
发布于 2017-04-22 09:01:52
当您的react.js应用程序加载时,react-router会在前端处理路由。比如说,你在http://a.com。然后在您导航到http://a.com/b的页面上。此路由更改将在浏览器本身中处理。现在,当您在新选项卡中刷新或打开url http://a.com/b时,请求将转到不存在特定路由的nginx,因此您将得到404。
为了避免这种情况,您需要为所有不匹配的路由加载根文件(通常是index.html),以便nginx发送该文件,然后由您在浏览器上的react应用程序处理该路由。要做到这一点,您必须对您的nginx.conf或sites-enabled进行以下更改
location / {
try_files $uri /index.html;
}这告诉nginx查找指定的$uri,如果找不到指定的$uri,则将index.html发送回浏览器。(更多细节请参见https://serverfault.com/questions/329592/how-does-try-files-work )
发布于 2020-05-12 13:56:27
这里给出的答案是正确的。但是,当我试图将我的React应用程序部署到一个码头容器中时,我正在努力解决这个问题。问题是,如何更改码头容器内的nginx信任。
步骤1:准备Dockerfile
# Stage 1
FROM node:8 as react-build
WORKDIR /app
COPY . ./
RUN yarn
RUN yarn build
# Stage 2 - the production environment
FROM nginx:alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=react-build /app/build /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]请参见命令行:COPY nginx.conf /etc/nginx/conf.d/default.conf。在这里,我们告诉Docker将nginx.conf文件从docker主机复制到docker容器。
nginx.conf步骤2:在应用程序根文件夹中有一个文件
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri /index.html;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}步骤3:现在构建码头映像并运行
$ docker build . -t react-docker这将成功地建立您的码头形象。要检查它,请运行
$ docker images现在快跑
$ docker run -p 8000:80 react-docker 然后导航到http://localhost:8000
这是受这个博客启发的。
发布于 2020-11-13 03:28:39
对我来说,解决办法是:
location / {
root /var/www/myapp/build;
index index.html;
try_files $uri /index.html$is_args$args =404;
}https://stackoverflow.com/questions/43555282
复制相似问题