单网页应用中,页面只有一个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/,但也应该是可以访问到的。