当你的才华不能撑起你的野心时,就是你该选择学习的时候了!

Vue项目部署到IIS后刷新页面404问题分析及解决方案

问题分析

当Vue项目(使用Vue Router的history模式)部署到IIS服务器时,刷新非根路径页面出现404错误,这是因为:

1. 客户端路由 vs 服务器路由:Vue Router的history模式使用客户端路由,URL变化时不会向服务器请求新页面
2. IIS默认行为:IIS会尝试查找与URL路径匹配的实际文件/目录(如`/home/woxue`),当找不到时返回404
3. 首次访问正常:从根路径进入应用时,Vue能正确加载,但直接访问或刷新子路由时IIS无法处理

解决方案:配置IIS URL重写规则(推荐)

1. 确保已安装IIS的URL Rewrite模块(可从Microsoft官网下载)

2. 在Vue项目的`dist`文件夹中添加`web.config`文件,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <defaultDocument>
            <files>
                <clear />
                <add value="index.html" />
                <add value="Default.htm" />
                <add value="Default.asp" />
                <add value="index.htm" />
                <add value="iisstart.htm" />
            </files>
        </defaultDocument>
    <rewrite>
      <rules>
        <rule name="Handle History Mode and custom 404/500" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
    </system.webServer>
</configuration>


3. 如果已存在`web.config`文件,只需添加`<rewrite>`部分到`<system.webServer>`中

方案2:改用hash模式
  修改Vue Router的配置(不推荐,因为URL会带有#号):

const router = new VueRouter({
  mode: 'hash',
  routes
})

验证步骤
部署修改后的配置

尝试直接访问 http://demo.xxx.net/home/woxue

刷新页面确认不再出现404错误

posted @ 2025-04-18 14:26  hofmann  阅读(563)  评论(0)    收藏  举报