先贴代码
server {
listen 80;
server_name m.motou.com;
location / {
root html/ypt-web;
index index.html;
try_files $uri $uri/ /index.html;
}
location /webpath {
root html;
index index.html;
# error
try_files $uri $uri/ /index.html;
# good
try_files $uri $uri/ /score/index.html;
}
}
需求
现有如下域名 m.motou.com 指向 A项目(vue单页面)
增加 m.motou.com/score 指向 score项目(vue单页面)
报错信息
直接指向score的文件是可以成功访问
指向score下的路由 会造成静态资源访问的是/下面的index.html的资源
项目目录:
- 项目A html/a
- index.html(引入了a.js)
- static
- a.js
- 项目B html/score
- index.html(引入了b.js)
- static
- b.js
访问 m.motou.com 访问路径为 html/a 正确指向项目A
访问路由 m.motou.com/wodetian 访问路径为 html/a 正确指向项目A
访问 m.motou.com/score 访问路径为 html/score 正确指向项目B
访问路由 m.motou.com/score/wodetian 访问路径为 html/a 错误 指向项目A
解决方案
try_files $uri $uri/ /score/index.html;
nginx 官方文档 try_files
语法: try_files file1 [file2 ... filen] fallback
默认值: none
上下文: location(当前位置)
该指令告诉Nginx测试每个存在的文件,并将找到的第一个文件用作URI。
如果找不到任何文件,则指向位置fallback (/webpath/score/index.html)。
它可以是文件路径或任何URI。
location / {
try_files index.html index.htm @fallback;
}
location @fallback {
root /var/www/error;
index index.html;
}
后记
我的天,以前没有注意过这个参数,害我搞了好久想不明白。还以为是vue的路由问题,整来整去。
总结出一个道理:在程序中 每一个字母 都有很重要的意义 注意语气和顿句