Vue Router history模式的配置方法及其原理

2020-06-14 06:27:52易采站长站整理
location
root
所指定的目录)下寻找
index.html
(这是nginx在端口后没有额外路径时的默认行为),目标目录下有这个文件吗?有!然后静态服务器返回给你这个文件,配合
vue-router
进行转发,自然可以(部分)正常显示。

但如果直接访问

http://localhost:8080/home
,静态服务器会去目标目录下寻找
home
文件,目标目录下有这个文件吗?没有!所以自然就404了。

配置后端

为了达到直接访问

http://localhost:8080/home
也可以成功的目的,我们需要对后端(这里即nginx)进行一些配置。

首先想想,要怎样才能达到这个目的呢?

在传统的

hash
模式中(
http://localhost:8080#home
),即使不需要配置,静态服务器始终会去寻找
index.html
并返回给我们,然后
vue-router
会获取
#
后面的字符作为参数,对前端页面进行变换。

类比一下,在

history
模式中,我们所想要的情况就是:输入
http://localhost:8080/home
,但最终返回的也是
index.html
,然后
vue-router
会获取
home
作为参数,对前端页面进行变换。那么在nginx中,谁能做到这件事呢?答案就是
try_files

首先看一下try_files的语法: try_files file … uri;

然后看一下官方文档对它的介绍:


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.

大意就是它会按照

try_files
后面的参数依次去匹配
root
中对应的文件或文件夹。如果匹配到的是一个文件,那么将返回这个文件;如果匹配到的是一个文件夹,那么将返回这个文件夹中