方案一 (这种方式容易被第三方劫持)
location /{
root /data/nginx/html;
index index.html index.htm;
error_page 404 /index.html;
}
方案二
location /{
root /data/nginx/html;
index index.html index.htm;
if (!-e $request_filename) {
rewrite ^/(.*) /index.html last;
break;
}
}
方案三 (vue.js官方教程里提到的https://router.vuejs.org/zh-cn/essentials/history-mode.html)
server {
listen 8888;#默认端口是80,如果端口没被占用可以不用修改
server_name localhost;
root E:/vue/my_project/dist;#vue项目的打包后的dist
location / {
try_files $uri $uri/ @router;#需要指向下面的@router否则会出现vue的路由在nginx中刷新出现404
index index.html index.htm;
}
#对应上面的@router,主要原因是路由的路径资源并不是一个真实的路径,所以无法找到具体的文件
#因此需要rewrite到index.html中,然后交给路由在处理请求资源
location @router {
rewrite ^.*$ /index.html last;
}
#.......其他部分省略
}
仅记录一下出现问题的解决方法,供大家参考
本文记录了三种在Nginx中配置以解决Vue.js项目中路由404问题的方法。方案一简单但易被第三方劫持;方案二通过if判断避免404;方案三参照Vue.js官方教程,使用try_files和@router实现。这些方案旨在确保SPA应用在刷新页面时仍能正常运行。
3221

被折叠的 条评论
为什么被折叠?



