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

Docker+WordPress+Nginx反向代理下Vite HMR失效问题求助

Docker环境下WordPress + Vite开发反向代理与HMR修复方案

核心问题

当前配置缺失Nginx到Vite开发服务的反向代理规则,导致:

  • 访问https://localhost.test/main.js返回404(Nginx无法定位该资源)
  • Vite热模块替换(HMR)无法通过localhost.test建立WebSocket连接,文件变化监听失效

解决方案

1. 修改Nginx反向代理配置(default.conf)

在server块中添加Vite开发服务的代理规则,同时支持WebSocket转发:

# 反向代理Vite开发服务及HMR连接
location ~* ^/(main\.js|@vite|vite\.svg|__vite_ping) {
    proxy_pass http://host.docker.internal:5137;
    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;

    # 适配WebSocket协议的HMR
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_cache_bypass $http_upgrade;
}

2. 调整Vite配置(vite.config.js)

更新Vite服务配置,使其适配反向代理环境,确保HMR消息正确路由:

import { defineConfig } from "vite";
import { resolve } from 'path';

export default defineConfig({
    plugins: [
        {
            handleHotUpdate({ file, server }) {
                if (file.endsWith('.php')) {
                    server.ws.send({ type: 'full-reload', path: '*' });
                }
            }
        }
    ],
    root: '',
    base: process.env.NODE_ENV === 'development'
        ? '/'
        : '/dist/',
    build: {
        outDir: resolve(__dirname, './dist'),
        emptyOutDir: true,
        manifest: true,
        rollupOptions: {
            input: {
                main: resolve(__dirname + '/main.js')
            },
        }
    },
    server: {
        host: true,
        cors: true,
        strictPort: true,
        port: 5137, // 固定Vite服务端口
        origin: "https://localhost.test", // 声明外部访问地址
        hmr: {
          host: "localhost.test",
          protocol: "wss", // 匹配HTTPS的WebSocket协议
          port: 443, // 通过Nginx的443端口转发HMR
        }, 
    }
})

3. 让Docker容器访问宿主机Vite服务

在docker-compose.yml的nginx服务中添加extra_hosts配置:

nginx:
    build:
      target: server
    image: localhost/nginx
    container_name: nginx
    restart: unless-stopped
    volumes:
      - wp_data:/var/www/html:ro
      - ./logs/nginx:/var/log/nginx
      - ./mytheme:/var/www/html/wp-content/themes/mytheme:ro
    ports:
      - 80:80
      - 443:443
    extra_hosts:
      - "host.docker.internal:host-gateway" # 允许容器访问宿主机服务
    depends_on:
      - wp
    networks:
      wp_net:
        aliases:
          - localhost.test

4. 确认WordPress脚本引用(functions.php)

现有配置无需修改,保持VITE_SERVER为https://localhost.test即可:

<?php
define('DIST_URI', get_template_directory_uri() . '/dist');
define('DIST_PATH', get_template_directory() . '/dist');

define('IS_VITE_DEVELOPMENT', true);

define('VITE_SERVER', 'https://localhost.test');
define('VITE_ENTRY_POINT', '/main.js');

// enqueue hook
add_action( 'wp_enqueue_scripts', function() {
    
    if (defined('IS_VITE_DEVELOPMENT') && IS_VITE_DEVELOPMENT === true) {

        function vite_head_module_hook() {
            echo '<script type="module" crossorigin src="'. VITE_SERVER . VITE_ENTRY_POINT . '"></script>';
        }

        add_action( 'wp_head', 'vite_head_module_hook' );
      
    } else {
        // 生产环境逻辑
    }
});

验证步骤

  1. 重启Nginx容器:docker-compose restart nginx
  2. 启动Vite开发服务:在mytheme目录执行yarn dev
  3. 访问https://localhost.test,检查控制台是否成功加载main.js
  4. 修改main.js或PHP文件,确认页面是否自动热更新

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 10:48:10