此前关于Angular的BrowserHistory方式的Nginx配置曾发过一篇总结文章(参见:Angular支持BrowserHistory的配置),但在SSR的实践过程中,不知是因为Angular的版本升级了(彼时Angular为7.x,目前为13.x),还是因为Nginx的更新缘故,发现原先的配置失效了,甚至包括当时和运维一同优化的配置版本:

nginxCopy code
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
server { listen 80; server_name domain; location / { rewrite .* /index.html break; proxy_pass http://localhost:3000; proxy_set_header Host $host; } location /api/ { proxy_pass http://localhost:8080/; proxy_set_header Host $host; } }
server { listen 80; server_name domain; location / { rewrite .* /index.html break; proxy_pass http://localhost:3000; proxy_set_header Host $host; } location /api/ { proxy_pass http://localhost:8080/; proxy_set_header Host $host; } }

无奈,只能继续摸索……

经过无数次nginx -s reload后,终于,找到了完美的解决方案。将其发布到线上测试,结果证实方案可行。

但,接入CDN后,新的问题出现了……因为CDN是单独的域名,因此对静态资源的访问将出现跨域问题;另外,还有缓存、gzip压缩问题(无关CDN)和IP透传问题——所有这些都需要修改Nginx配置。

实际上,此方案适合所有单页应用(SPA)构建的伪多页架构,包括Angular、React、Vue等。

具体配置如下: