如何绕开 browser router 中不存在路由?

2019-12-14 21:27:46 +08:00
 orzorzorzorz

背景

Angular 的单页应用中因为有用到锚点,所以只能用 browser router。假设目标地址为 app.com/target1。

问题

在访问 app.com/target1 时,路由跳转到 app.com/target1/target2, 刷新页面后 404。

相关配置如下:

server {
  listen 4300;
  server_name business;

  location / {
    try_files $uri $uri/ /index.html;
    root tempPath/dist/;
  }
}

server {
  listen 80;
  server_name entry;
  root tempPath/;

  location ^~ /business {
    proxy_pass http://localhost:4300;
  }
}

尝试的解决方法

  1. 关键字搜了 browser router with nginx,看到的都是用 try_files $uri $uri/ /index.html。我试着把最后一个参数改成 app.com/target1 所在的物理路径,也就是 tempPath/dist/,错误日志会说:rewrite or internal redirection cycle while internally redirecting to "/index.html" 。后来想想,逻辑上确实是循环,此路不通。

  2. 从页面物理层面解决。就是每个路由都写个 html,但这真的很麻烦...

希望获得帮助的点

希望能在 1 的方向上给点建议。看上去只要在匹配到 /business 时停下来,直接转发到 html 入口就能解决了...

3479 次点击
所在节点    NGINX
7 条回复
beginor
2019-12-15 11:36:43 +08:00
直接在 80 端口下面 try_files 不行么,为啥还要再转一下?
orzorzorzorz
2019-12-15 12:15:57 +08:00
@beginor 80 端口得监听很多像这样的 app,有 app.com/target1,有 app.com/target2,我希望能写得更清晰一点就转了。实际上直接在 80 try_files 报的错跟正文里的写法报的错是一样的。
beginor
2019-12-15 13:45:31 +08:00
我一般是这样写的,参考一下:
```
location /app/web/ {
alias /app/web/;
index index.html index.htm;
add_header Cache-Control no-cache;
gzip_static on;
try_files $uri /app/web/index.html;
}
```
KuroNekoFan
2019-12-16 09:09:26 +08:00
约定一种 url 模式,访问这种模式的 url 都 fallback 到 html 入口文件,location 跟 router 的 basename 对应起来
最后,如果你的 js,css 什么的跟 html 在同一个 location 里,记得上面约定的 url 模式不要跟访问 js/css 的 url 模式冲突
orzorzorzorz
2019-12-16 09:53:22 +08:00
@KuroNekoFan 是说 nginx 一层路由,入口 html 一层转发,app 一层路由,这样吗?好吧,如果是这样,那在只改 nginx 层面上估计是没办法了。
感谢回复。
orzorzorzorz
2019-12-16 09:56:35 +08:00
@KuroNekoFan 呃,没别的嘲讽的意思,你的回答的确是能绕开 nginx 的路由匹配。我原先的表达也有问题,我本来是以为只改 nginx 的配置就能实现这类路由的,只是我没翻到文档...
KuroNekoFan
2019-12-16 10:20:59 +08:00
我说的就是 nginx 啊,当然,不能光改 nginx,还需要用配合的 webpack publicPath,和 browserRouter 的 baseName
nginx 配置如下

```
#注意这个 location map 应该要以 /结尾
location /your/desired/path/ {
alias $your_web_dir_root;
#url without a dot
location ~ ^[^.]*$ {

try_files your_html_file.html =404;
}
}
```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/629098

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX