vue-router mode设置为history时,nginx要添加以下try_files配置:
location / {
root /www/fe/;
index index.html index.htm index.php;
try_files $uri $uri/ /index.html;
}
假如按照以上配置,访问https://juejin.cn/editor时, $uri 就是取查找 editor。
- 因此先查找是否有
/$root/$uri(即/www/fe/editor)文件,如果有,则返回该文件内容。 - 否则,则查找
/$root/$uri/(即/www/fe/editor/)目录下是否有index.html、index.htm、index.php文件,如果有,则返回该文件内容。 - 当然,一般情况下上面两种情况都不会出现,因此会返回
/$root/index.html(即/www/fe/index.html)文件内容,该文件就是我们打包生成的dist目录下的html文件。
服务器返回index.html文件内容给浏览器,并加载该文件依赖的js和css文件。与此同时浏览器地址栏的url还是https://juejin.cn/editor,脚本通过这个url解析出对应的路由地址并展示页面内容。
如果要在url中加上子目录的话,如https://juejin.cn/fe/editor,需要将nginx配置改为:
location /fe/ {
root /www/;
index index.html index.htm index.php;
try_files $uri $uri/ /fe/index.html;
}
同时,要修改一下vue-router的base参数,使路由跳转带上子目录:
const router = new VueRouter({
base:'fe',
mode:'history',
routes: [
...
]
}