HTML5模式下的NGINX,proxy_pass和SPA路由

时间:2017-08-04 08:56:40

标签: html5 angular nginx

我将NGINX设置为一个反向代理,用于将自身作为容器运行的docker容器的虚拟网络。其中一个容器提供基于Angular 4的SPA,在HTML5模式下具有客户端路由。

应用程序映射到NGINX上的位置/,以便http://server/将您带到SPA主屏幕。

server {
    listen 80;

    ...

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

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

    ...
}

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

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

我发现配置NGINX以支持这种情况的例子总是假设SPA的静态内容直接来自NGINX,因此try_files是一个可行的选择。

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

1 个答案:

答案 0 :(得分:7)

对我有用的解决方案是将指令proxy_intercept_errorserror_page添加到NGINX中的location /

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中解析它。

当然,现在SPA负责处理“真正的”404。幸运的是,无论如何,这都不是SPA中的问题和良好做法。