nginx配置vue history模式,多层路由无法正常显示,请问怎么解决?

按照vue官网配置单页面history模式
配置如下

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

说明:html文件夹是nginx根目录,html文件夹和nginx.exe同级。
打开http://localhost/home或者http://localhost能正常访问,刷新无问题,点击页面a标签,路由切换到http://localhost/home/nextpage,也能正常显示,但是
如果直接刷新http://localhost/home/nextpage,这时候就出现错误

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

查看控制台时看到

http://localhost/home/assets/index.a18e7567.js

感觉原因出现在/home/路径,因为项目根目录下根本没有name文件夹,所以http://localhost/assets/index.a18e7567.js才是正确的,去掉/home就好了

请问这是为什么,我应该怎么配置nginx?

这里是我的nginx和配置
https://github.com/qiaen/dany...
我放到github了

阅读 8.2k
2 个回答

更新,这个问题已经解决,光是try_files $uri $uri/ /index.html还不够,要让文件从根目录获取,还需要加上proxy_set_header Host $host谢谢其他大佬的指导。

location / {
    root html/前端代码文件夹/;
    # 关键部分
    proxy_set_header Host $host;
    try_files $uri $uri/ /index.html;
}

推测已经不是 nginx 的配置问题,考虑到你的实际生产部署目录是 / 即根目录,确认一下你的 vue.config.jspublicPath 是不是 /

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题