域名下子路径修改

lishihuan大约 5 分钟

域名下子路径修改

下面的项目以 http://test.local.com/iws/XJB/open in new window 为例

项目初始访问的62.190.54.213:19091,后面改域名的方式,需要追加/iws/XJB/ 这两层子目录

  • public/index.html 中需要修改引用的静态资源
  • vue.config.js中需要指定publicPath
  • env文件中定义 VUE_APP_BASE_API变量记录请求url前缀-
  • Router路由中添加base属性

目前项目env分为 production和development

生产production

# 生产环境配置
NODE_ENV = production

# 二级域名服务的子路径  后期服务修改为 域名/iws/XJB/ 这样的方式访问
VUE_APP_SUB_PATH = '/iws/XJB'

# i皖送 cas 服务url
VUE_APP_IWS_URL_CAS = 'http://test.local.com/iws/cas/'

# 生产环境配置
VUE_APP_BASE_API = '/iws/XJB/stage-api'

开发development

# 开发环境配置
ENV = 'development'

# 二级域名服务的子路径  后期服务修改为 域名/iws/XJB/ 这样的方式访问
VUE_APP_SUB_PATH = ''

# i皖送 cas 服务url
VUE_APP_IWS_URL_CAS = '/'

# 开发环境
VUE_APP_BASE_API = '/dev-api'

# 路由懒加载
VUE_CLI_BABEL_TRANSPILE_MODULES = true

1. public/index.html

需要给静态资源文件添加 /iws/XJB/ 为了方便开发 结合env文件使用 <%= process.env.VUE_APP_SUB_PATH %>

 <script src="<%= process.env.VUE_APP_SUB_PATH %>/sm2/sm2.js"></script>

2. vue.config.js

默认开发是/ 当前需要添加 /iws/XJB/

publicPath: process.env.NODE_ENV === "production" ? "/iws/XJB/" : "/",

3. env文件

VUE_APP_BASE_API = '/dev-api' 改为 VUE_APP_BASE_API = '/iws/XJB/stage-api'

4. Router路由

指定 base 属性 /iws/XJB/

export default new Router({
    mode: 'history', // 去掉url中的#
    base: process.env.VUE_APP_SUB_PATH,// 域名服务下的子路径  后期服务修改为 域名/iws/XJB/ 这样的方式访问
    scrollBehavior: () => ({
        y: 0
    }),
  stringifyQuery: stringifyQuery,
  parseQuery: parseQuery,
    routes: constantRoutes
})

额外补充

  • 拆包

打包后文件超出10M 被拦截,需要进行拆分,通过修改vue.config.js 来实现

vue.config.js

cacheGroups: {
              // 以下代码经过改动
              libs: {
                name: 'chunk-libs',
                test: /[\\/]node_modules[\\/]/,
                priority: 10,
                chunks: 'initial' // only package third parties that are initially dependent
              },
              elementUI: {
                name: 'chunk-elementUI', // split elementUI into a single package
                priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
              },
              vendors: {//vendor 是导入的 npm 包
                name: 'chunk-vendors',
                //  test: /[\\/]node_modules[\\/]/,
                chunks: 'all',
                maxSize: 5000,
                priority: 2,
                reuseExistingChunk: true,
                enforce: true
              },
              commons: {
                name: 'chunk-commons',
                // test: resolve('src/components'), // can customize your rules
                chunks:'all',
                minChunks: 3, //  minimum common number
                priority: 5,
                maxSize:5000,
                reuseExistingChunk: true
              }
            }
  • nginx配置

iws中的nginx配置,需要注意 /

location /XJB/ {
	proxy_pass http://192.168.55.107:19091/;
}

Vue 项目部署到子目录+nginx 部署 ,现在页面刷新丢失

当使用 Vue Router 的 history 模式 并部署到子目录(如 /APP)时,页面刷新或直接访问子路径会触发以下问题:

  1. Nginx 未正确回退到 index.html,导致请求直接返回 404。
  2. 前端静态资源路径未适配子目录(JS/CSS 加载失败)。
  3. Vue Router 未配置 base,导致路由路径拼接错误。

解决方案

.env文件中配置 VUE_APP_SUB_PATH = 'APP'

步骤 1:配置 Vue 项目的 publicPath

修改 vue.config.js,确保静态资源路径指向子目录:

// vue.config.js
module.exports = {
  publicPath: process.env.NODE_ENV === 'production' 
    ? process.env.VUE_APP_SUB_PATH+'/'  // 生产环境子目录
    : '/',           // 开发环境根目录
  // 其他配置...
}

步骤 2:配置 Vue Router 的 base

在路由配置中指定子目录基准路径:

// src/router/index.js
const router = new VueRouter({
  mode: 'history',
  base: process.env.VUE_APP_SUB_PATH,
  routes
});

步骤 3:修正 Nginx 配置【这里以APP 为子目录 】

这里是核心,try_files $uri $uri/ /APP/index.html; 需要指定 /APP/ 否则会导致刷新丢失页面

修改 Nginx 的 try_files 指令,强制回退到子目录下的 index.html

location /APP {
  alias /home/SDT_ZHST/dist/;  # 确保路径末尾有斜杠
  try_files $uri $uri/ /APP/index.html;  # 关键修正!
  index index.html;
}

步骤 4:验证静态资源路径

如果 public/index.html 中有本地js的引入,则需要手动补全

<!-- 正确路径应包含子目录 -->
<script src="<%= process.env.VUE_APP_SUB_PATH %>/sm2/crypto-js.js"></script>

步骤 5:处理开发环境路由(可选)【没加过,应该不需要】

在本地开发时模拟子目录行为,修改 vue.config.js

module.exports = {
  devServer: {
    historyApiFallback: {
      rewrites: [
        { from: /\/APP/, to: '/APP/index.html' }
      ]
    }
  }
}

步骤 6:重启服务并清除缓存

  1. 重新构建项目:
    npm run build
    
  2. 重新加载 Nginx:
    nginx -s reload
    
  3. 清除浏览器缓存或使用无痕模式测试。

完整 Nginx 配置示例

server {
  listen 19095;
  server_name localhost;
  server_tokens off;

  # 主应用子目录
  location /APP {
    alias /home/YJ_ZHST/dist/;
    try_files $uri $uri/ /APP/index.html;
    index index.html;
  }

  # 其他路由...
  location /stage-api/ {
    proxy_pass http://zhst-stage-api-server/;
    # 代理配置...
  }

  # 静态文件服务
  location /files {
    alias /home/SDT_ZHST/bonus/file/;
    autoindex off;
  }

  error_page 500 502 503 504 /50x.html;
  location = /50x.html {
    root html;
  }
}

故障排查表

现象可能原因检查点
页面空白静态资源路径错误查看浏览器控制台网络请求
路由跳转 404Nginx 未回退到 index.html检查 try_files 配置
部分接口 404代理路径未正确配置检查 proxy_pass 结尾斜杠
本地开发异常publicPath 未区分环境确认 process.env.NODE_ENV

通过以上步骤,可确保 Vue 项目在子目录部署后实现:

  • ✅ 页面刷新正常
  • ✅ 静态资源正确加载
  • ✅ 前端路由无缝跳转

以若依微服务为例,前端修改

在上面的基础上,优化退出

  • 修改.env文件
# 统一认证中心地址
VUE_APP_IWS_URL_CAS = 'http://192.168.2.231:19095/'

# 控制是否显示登录界面--正式环境通过 统一认证中心地址
VUE_APP_IWS_IFKY = true
  • 添加一个utils ,控制退出
// src/utils/redirect.js
// 跳转到主服务登录页或本地首页
export function redirectToLoginOrIndex() {
  if (process.env.VUE_APP_IWS_IFKY === 'true') {
    window.location.href = process.env.VUE_APP_IWS_URL_CAS;
  } else {
    window.location.href = '/index';
  }
}

  • 所有涉及主服务/本地跳转的地方(src/permission.js、src/layout/components/Navbar.vue、src/layout/index.vue、src/utils/request.js)全部统一调用该函数
this.$store.dispatch('LogOut').then(() => {
          redirectToLoginOrIndex();// 新增
})
  • src/permission.js 路由拦截器中
if (whiteList.indexOf(to.path) !== -1) {
      if (isIwsIfky) {
        redirectToLoginOrIndex()
      } else {
        next()
      }
    } else {
      if (isIwsIfky) {
        redirectToLoginOrIndex()
      } else {
        next(`/login?redirect=${encodeURIComponent(to.fullPath)}`)
        NProgress.done()
      }
    }