前端单网页应用history下配置nginx路由

单网页应用中,页面只有一个index.html的入口文件。如果使用history模式,对于不同的url我们希望最终都可以访问到index.html。

一般公司都会使用nginx作为其对外的服务器。在vue-router的官网上,实际上已经写出了如何配置:

location / {
  try_files $uri $uri/ /index.html;
}

可是看起来不那么好懂,我用简化配置:

location / {
  try_files c.html b.html a.html defult.html
}

看起来是不是好懂一些了?try_files就是尝试挨个按照给定的顺序找文件,找到就处理。

即服务器中若有c.html,就返回c.html,若没有,就找b.html…依次类推。比较特殊一点是最后一个,这个一个fallback,也就是理论上他一定有,这个一个默认页,用于处理什么也没找的情况。

Checks the existence of files in the specified order and uses the first found file for request processing; the processing is performed in the current context. The path to a file is constructed from the file parameter according to the root and alias directives. It is possible to check directory’s existence by specifying a slash at the end of a name, e.g. “$uri/”. If none of the files were found, an internal redirect to the uri specified in the last parameter is made.

而vue-router中的配置也恰恰利用了这一点,若什么也没有,就fallback到index.html,这不正是我们希望的么?

再来看一下他的配置:先尝试找$uri 然后找$uri/,找不到就返回index.html。

  • $uri是一个变量,就是指当前访问url。因为我们使用history模式配了路由,所以理论上你肯定找不到这个,当然静态资源bundle.js这类的是可以找到的。
  • $uri/是第二个要找的,为什么需要有他呢?因为有时候我们访问页面不会指明index.html。比如我希望访问dist/index.html。而实际上,访问的网址仅仅是dist/,但也应该是可以访问到的。
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值