You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker+Nginx环境下Vue Router刷新页面返回404问题

Vue Router history模式刷新/直接访问路由404问题解决

问题描述

我有一个Docker容器化的Vue.js应用,Vue Router启用了history模式。通过应用内链接导航一切正常,但刷新页面或直接访问路由时会出现404 Not Found错误。

环境配置

  • Vue应用Docker容器化部署
  • Nginx作为反向代理提供服务
  • 访问路径为/dev/myapp/
  • 后端服务运行在6991端口

当前Nginx配置

location /dev/myapp/ {
    proxy_pass http://localhost:6991/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

解决方案

1. 修改Nginx配置

需要添加try_files指令,让所有路由请求都转发到Vue应用的入口文件index.html,由Vue Router接管路由处理。修改后的配置如下:

location /dev/myapp/ {
    proxy_pass http://localhost:6991/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    # 处理history模式路由,找不到资源时转发到入口文件
    try_files $uri $uri/ /dev/myapp/index.html;
}

2. 同步调整Vue项目配置

在项目根目录的vue.config.js中设置publicPath,确保应用资源路径正确指向访问前缀:

module.exports = {
  publicPath: '/dev/myapp/'
}

说明

  • Nginx的try_files指令会优先匹配请求的文件或目录,若匹配失败则转发到/dev/myapp/index.html,让Vue Router处理路由逻辑,避免404。
  • 配置publicPath是为了保证应用内的静态资源(如JS、CSS、图片)能正确加载,路径不会出现错误。

内容的提问来源于stack exchange,提问作者eilwa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 04:48:12