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

Vite 5.1.4中缺失图片返回index.html而非404,如何修复?

解决Vite 5.1.4中缺失图片返回index.html而非404的问题

问题原因

Vite默认启用**SPA历史回退(historyApiFallback)**机制,所有未匹配到实际文件的请求都会被重定向到index.html——这是为了支持单页应用的前端路由,但会导致缺失的静态资源(比如图片)也返回index.html而非404。

解决方案

方案1:自定义historyApiFallback规则(适用于SPA应用)

修改vite.config.js(或vite.config.ts),通过重写规则让静态资源请求在文件不存在时返回404:

import { defineConfig } from 'vite'
import fs from 'fs'
import path from 'path'

export default defineConfig({
  server: {
    historyApiFallback: {
      rewrites: [
        // 处理静态资源请求:文件不存在则返回404
        {
          from: /\.(jpg|jpeg|png|gif|svg|webp|ico)$/,
          to: (context) => {
            // 拼接实际文件路径(假设静态资源放在public目录)
            const filePath = path.resolve(__dirname, 'public', context.parsedUrl.pathname.slice(1))
            if (!fs.existsSync(filePath)) {
              // 返回404状态,可替换为自定义404页面路径(如'/404.html')
              context.res.writeHead(404, { 'Content-Type': 'text/plain' })
              context.res.end('404 Not Found')
              return null
            }
            // 文件存在则正常返回资源
            return context.parsedUrl.pathname
          }
        },
        // 保留SPA路由的默认 fallback 规则
        { from: /./, to: '/index.html' }
      ]
    }
  }
})

方案2:添加自定义服务器中间件

通过configureServer注入中间件,直接拦截静态资源请求并校验文件存在性:

import { defineConfig } from 'vite'
import fs from 'fs'
import path from 'path'

export default defineConfig({
  server: {
    async configureServer(server) {
      server.middlewares.use((req, res, next) => {
        const reqUrl = req.url
        // 匹配常见图片后缀
        if (/\.(jpg|jpeg|png|gif|svg|webp|ico)$/.test(reqUrl)) {
          const filePath = path.resolve(__dirname, 'public', reqUrl.slice(1))
          if (!fs.existsSync(filePath)) {
            // 返回404状态码和内容
            res.writeHead(404, { 'Content-Type': 'text/plain' })
            res.end('404 Not Found')
            return
          }
        }
        // 非静态资源请求,继续执行后续中间件
        next()
      })
    }
  }
})

方案3:关闭SPA fallback(仅适用于非SPA项目)

如果你的项目不是单页应用,可直接关闭historyApiFallback,所有未匹配的请求都会返回404:

import { defineConfig } from 'vite'

export default defineConfig({
  server: {
    historyApiFallback: false
  }
})

注意事项

  • 若静态资源存放在src/assets而非public,需调整filePath的解析路径(开发环境下Vite会对src/assets资源做特殊处理,可通过server.fs.allow配置允许访问的目录)。
  • 自定义404页面时,需在public目录下创建对应的404.html,并修改返回路径为'/404.html'。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 04:14:53