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

如何根据vue.config.js的devServer.https设置控制Vue项目HTTP转HTTPS跳转

Vue项目中根据devServer.https配置控制HTTPS重定向

实现思路

通过Webpack的DefinePlugin将vue.config.js里的devServer.https配置注入为全局环境变量,在业务代码中结合环境变量判断是否执行重定向逻辑。

步骤1:修改vue.config.js,注入环境变量

先把devServer.https的配置单独抽离,再通过DefinePlugin将其注入到项目的全局环境中:

const { defineConfig } = require('@vue/cli-service')
// 单独定义devServer的https配置,方便后续复用
const isDevServerHttps = false

module.exports = defineConfig({
  devServer: {
    https: isDevServerHttps
  },
  configureWebpack: {
    plugins: [
      new require('webpack').DefinePlugin({
        // 将配置转为JSON字符串注入,确保前端能正确读取
        'process.env.VUE_APP_DEV_SERVER_HTTPS': JSON.stringify(isDevServerHttps)
      })
    ]
  }
})

步骤2:修改重定向代码,加入配置判断

在原来的重定向逻辑中,增加环境变量的判断:只有生产环境,或者开发环境下devServer.https为true时,才执行HTTP转HTTPS的重定向:

// 生产环境默认强制重定向;开发环境根据devServer配置决定
const needRedirect = (process.env.NODE_ENV === 'production' || process.env.VUE_APP_DEV_SERVER_HTTPS) 
  && location.protocol !== 'https:'

if (needRedirect) {
  console.info('redirecting!')
  location.replace(`https:${location.href.substring(location.protocol.length)}`)
} else {
  console.info('not redirecting...')
}

补充说明

  • 生产环境下无论配置如何,都会执行重定向,符合你“双重保障”的需求;
  • 开发环境中,当devServer.https设为false时,会跳过重定向逻辑,避免本地开发时的不必要跳转。

内容的提问来源于stack exchange,提问作者Eric Brown - Cal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 01:24:29