我将 NGINX 设置为 docker 容器虚拟网络的反向代理,该虚拟网络将自身作为容器运行。其中一个容器以 HTML5 模式为基于 Angular 4 的 SPA 提供客户端路由服务。
应用程序映射到位置/在 NGINX 上,因此 http://server/将您带到 SPA 主屏幕。
server {
listen 80;
...
location / {
proxy_pass http://spa-server/;
}
location /other/ {
proxy_pass http://other/;
}
...
}
Angular 路由器将 URL 更改为 http://server/home或在 SPA 内导航时的其他路线。
但是,当我尝试直接访问这些 URL 时,返回了 404。此错误源自 spa-server
,因为它显然没有这些路由的任何内容。
我找到的配置 NGINX 以支持这种情况的示例始终假定 SPA 的静态内容直接从 NGINX 提供,因此 try_files
是一个可行的选项。
如何将任何未知的 URL 转发到 SPA 以便它自己处理它们?
最佳答案
对我有用的解决方案是将指令 proxy_intercept_errors
和 error_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 将返回/index.html,即来自 spa-server
的 SPA。尽管如此,该 URL 仍可供 Angular 使用,路由器将立即在 SPA 中解析它。
当然,现在 SPA 负责处理“真正的”404。幸运的是,无论如何这在 SPA 中不是问题和良好实践。
更新:感谢@dan
关于html - HTML5 模式下的 NGINX、proxy_pass 和 SPA 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45502403/