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

无需重写规则或HashRouter,如何解决IIS上React路由404问题?

问题

将React应用部署至IIS Web Server后出现页面404问题,已知两种解决方式:

  • 配置web.config重写规则,将请求指向index.html
  • 使用HashRouter包裹路由(但URL会带有/#/)

当前React应用的路由配置如下:

<Switch> 
  <Route exact path="/Documents/Home" component={Home} /> 
  <Route exact path="/Documents" component={Documents} /> 
  <Route component={NotFoundPage} /> 
</Switch>

已有的web.config重写规则示例:

<?xml version="1.0" encoding="UTF-8"?>
  <configuration>
     <system.webServer>
        <rewrite>
          <rules>
            <rule name="ReactRouter Routes" stopProcessing="true">
              <match url=".*" />
                 <conditions logicalGrouping="MatchAll">
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                 </conditions>
              <action type="Rewrite" url="index.html" />
           </rule>
         </rules>
       </rewrite>
    </system.webServer>
</configuration>

HashRouter配置示例:

<HashRouter>
  <Switch> 
    <Route exact path="/Documents/Home" component={Home} /> 
    <Route exact path="/Documents" component={Documents} /> 
    <Route component={NotFoundPage} /> 
  </Switch>
</HashRouter>

现咨询是否存在第三种解决该IIS上React路由问题的方法?


第三种解决方法

可以将React应用部署为IIS的应用程序(Application),并配合BrowserRouter的basename属性适配路径,具体步骤如下:

  1. IIS端配置:
    • 在目标IIS站点下创建新应用程序,别名设置为你的路由根路径(比如Documents)
    • 将React打包后的build文件夹内容,部署到该应用程序对应的物理路径
  2. React路由修改:
    • 使用BrowserRouter包裹路由,通过basename属性指定IIS应用程序的别名,同时调整路由路径去掉前缀:
      <BrowserRouter basename="/Documents">
        <Switch> 
          <Route exact path="/Home" component={Home} /> 
          <Route exact path="/" component={Documents} /> 
          <Route component={NotFoundPage} /> 
        </Switch>
      </BrowserRouter>
      

这种方式既不需要配置URL重写规则,也不会出现HashRouter的/#/路径,同时能让IIS正确识别路由路径,避免404问题。


内容的提问来源于stack exchange,提问作者It's Just a Printer Driver

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 16:05:25