无需重写规则或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属性适配路径,具体步骤如下:
- IIS端配置:
- 在目标IIS站点下创建新应用程序,别名设置为你的路由根路径(比如
Documents) - 将React打包后的
build文件夹内容,部署到该应用程序对应的物理路径
- 在目标IIS站点下创建新应用程序,别名设置为你的路由根路径(比如
- 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
相关产品推荐
相关产品推荐

