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

Vite多页应用开发服务器如何配置无.html后缀的自定义访问URL

实现方案

完全可以实现,你需要同步调整Vite开发服务器规则,以及后续生产环境的部署配置,具体操作如下:

1. 开发环境配置修改

你可以通过Vite内置的configureServer钩子添加路由重写逻辑,直接将不带.html后缀的路径映射到对应页面文件,修改后的完整配置参考如下:

// vite.config.js
export default {
  build: {
    rollupOptions: {
      input: {
        index: new URL('./index.html', import.meta.url).pathname,
        login: new URL('./login.html', import.meta.url).pathname,
      }
    }
  },
  server: {
    port: 3010,
    proxy: {
      '/api': 'http://localhost:5000/',
    },
    // 新增路由重写配置
    configureServer(server) {
      server.middlewares.use((req, res, next) => {
        // 仅针对login路径匹配,要适配其他页面可以放开下方的批量规则
        if (req.url.startsWith('/login') && !req.url.includes('.')) {
          req.url = '/login.html';
        }
        // 批量适配所有页面写法:排除接口、静态资源后自动补全.html后缀
        // if (!req.url.includes('.') && !req.url.startsWith('/api')) {
        //   req.url += '.html';
        // }
        next();
      })
    }
  },
};

修改配置后重启开发服务器,即可直接通过localhost:3010/login访问登录页。

2. 生产环境部署适配

上述配置仅在开发环境生效,项目打包部署到生产环境时,需要同步配置Web服务器的重写规则:

  • Nginx部署可在server块中添加如下规则:
    location / {
      try_files $uri $uri.html $uri/ =404;
    }
    
  • 其他部署平台可对应查找平台官方的路径重写规则配置即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 17:42:01