HTML5模式下的NGINX,proxy_pass和SPA路由 [英] NGINX, proxy_pass and SPA routing in HTML5 mode

查看:45
本文介绍了HTML5模式下的NGINX,proxy_pass和SPA路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将NGINX设置为运行本身作为容器的docker容器虚拟网络的反向代理.这些容器之一可为基于Angular 4的SPA提供HTML5模式的客户端路由.

I have NGINX set up as a reverse proxy for a virtual network of docker containers running itself as a container. One of these containers serves an Angular 4 based SPA with client-side routing in HTML5 mode.

该应用程序已映射到NGINX上的location/,因此 http://server/会将您带到SPA主屏幕

The application is mapped to location / on NGINX, so that http://server/ brings you to the SPA home screen.

server {
    listen 80;

    ...

    location / {
        proxy_pass http://spa-server/;
    }

    location /other/ {
        proxy_pass http://other/;
    }

    ...
}

在SPA中导航时,Angular路由器会将URL更改为 http://server/home 或其他路由.

The Angular router changes the URL to http://server/home or other routes when navigating within the SPA.

但是,当我尝试直接访问这些URL时,将返回404.此错误源自 spa-server ,因为显然这些路由没有任何内容.

However, when I try to access these URLs directly, a 404 is returned. This error originates from the spa-server, because it obviously does not have any content for these routes.

我发现的配置NGINX以支持这种情况的示例始终假定SPA的静态内容直接由NGINX提供,因此 try_files 是一个可行的选择.

The examples I found for configuring NGINX to support this scenario always assume that the SPA's static content is served directly from NGINX and thus try_files is a viable option.

如何将任何未知的URL转发到SPA,以便它可以自行处理?

How is it possible to forward any unknown URLs to the SPA so that it can handle them itself?

推荐答案

对我有用的解决方案是将 proxy_intercept_errors error_page 指令添加到NGINX中的位置/:

The solution that works for me is to add the directives proxy_intercept_errors and error_page to the location / in NGINX:

server {
    listen 80;

    ...

    location / {
        proxy_pass http://spa-server/;
        proxy_intercept_errors on;
        error_page 404 = /index.html;
    }

    location /other/ {
        proxy_pass http://other/;
    }

    ...
}

现在,每当请求未知URL时,NGINX将从 spa-server 返回/index.html,即SPA.该URL仍然可供Angular使用,路由器将立即在SPA中解析它.

Now, NGINX will return the /index.html i.e. the SPA from the spa-server whenever an unknown URL is requested. Still, the URL is available to Angular and the router will immediately resolve it within the SPA.

当然,现在SPA负责处理真实" 404.幸运的是,无论如何这不是SPA中的问题,而是一种好的做法.

Of course, now the SPA is responsible for handling "real" 404s. Fortunately, this is not a problem and a good practice within the SPA anyway.

更新:感谢@dan

这篇关于HTML5模式下的NGINX,proxy_pass和SPA路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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