IIS部署React SPA使用Rewrite Module无法访问独立子目录问题求助
解决方案
你当前使用的重写规则仅排除了「真实存在的文件」类请求,没有排除真实存在的目录请求,所以访问/Dev这个独立子目录时,请求会被重写到React的入口index.html,进入React Router的路由匹配逻辑,自然无法正常访问子目录内容。
方案1:通用排除所有真实目录(推荐)
直接在现有规则的条件节点下新增IsDirectory的否定判断,所有真实存在的目录都不会被React路由规则拦截,适合需要部署多个独立子目录的场景。
修改后的完整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" /> <!-- 新增下面这行,排除真实存在的目录请求 --> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="index.html" /> </rule> </rules> </rewrite> </system.webServer> </configuration>
方案2:仅排除指定/Dev目录
如果不想放开所有目录的访问权限,只需要单独放行/Dev目录,可以加路径匹配的否定条件:
<?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" /> <!-- 新增下面这行,仅排除/Dev开头的路径 --> <add input="{REQUEST_URI}" pattern="^/Dev(/.*)?$" negate="true" /> </conditions> <action type="Rewrite" url="index.html" /> </rule> </rules> </rewrite> </system.webServer> </configuration>
修改配置后保存,重启对应IIS站点或者回收应用池即可生效,直接访问http://{REACT_SPA}/Dev就能正常进入子目录。
内容的提问来源于stack exchange,提问作者yush
相关产品推荐
相关产品推荐

