nginx 响应 404 Not Found(单页应用程序) [英] nginx responds with 404 Not Found (Single Page App)

查看:104
本文介绍了nginx 响应 404 Not Found(单页应用程序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有常规浏览器路由器的单页应用程序(没有散列).每当有人浏览页面并点击刷新按钮时,nginx 都会尝试在此路径上查找文件.因此,如果有人在 mypage.com/about 上,nginx 会查找 about 文件并以 404 Not Found 响应.如何解决这个问题?

I have a Single Page Application with regular Browser Router (without hash). Whenever someone navigates through page and hits refresh button nginx tries to find file on this path. So if someone is on mypage.com/about nginx looks for about file and responds with 404 Not Found. How to fix this issue?

我正在考虑使用通配符指定一个位置 - mypage.com/* 除了 /api tho,因为这个应用程序中的每个后端端点都以 开头api.如何匹配除一条之外的所有路径?这是我的配置的样子:

I'm thinking about specifying a location with wildcard - mypage.com/* except /api tho, because every backend endpoint in this app starts with api. How to match all paths except one? This is how my config looks like:

upstream frontend {
    server frontend:3000;
}

upstream backend {
    server backend:8000;
}

server {
    listen 80;

    location /api {
        proxy_pass http://backend;
        proxy_set_header Host            \$http_host;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
    }

    location / {
        proxy_pass http://frontend;
        proxy_redirect default;
    }
}

推荐答案

为什么你的前端应用会请求代理?我假设您正在使用某种开发服务器来为您的前端应用程序提供服务.最好将您的前端应用程序构建为静态文件并将它们作为常规静态文件提供,除了 nginx 之外没有任何服务器.

Why do your proxy requests for frontend app ? I assume that you are using some kind of development server to serve your frontend application. It is better to build your frontend application to static files and serve them as regular static files, without any server except the nginx.

至于您的问题,如果您将前端应用程序构建到静态文件中,您可以像这样在 nginx 中配置位置:

As for your question, if you will build your frontend application into static files you may configure location in nginx like this:

root /var/www/your_site;
location / {
    try_files $uri /index.html;
}

其中 index.html 是应用程序的入口点,并且根路径应配置为存放它的位置.

where index.html is entrypoint into your application and the root path should be configured to place where it stored.

如果您仍然想通过 nginx 从开发服务器提供前端应用程序,您可以配置 nginx 来处理来自上游的错误并将错误页面指向开发服务器的根目录.

If you still want to serve frontend application from development server through nginx you may configure nginx to handle errors from upstream and point error page to root of dev server.

在这种情况下,以下指令应该对您有所帮助:http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_intercept_errorshttp://nginx.org/en/docs/http/ngx_http_core_module.html#error_page

In this case following directives should help you: http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_intercept_errors http://nginx.org/en/docs/http/ngx_http_core_module.html#error_page

这篇关于nginx 响应 404 Not Found(单页应用程序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆