You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

React SPA与WebAPI同IIS部署时app_offline.htm不生效问题咨询

解决IIS中app_offline.htm被React重写规则覆盖的问题

你遇到的问题确实是因为URL重写规则的优先级高于IIS内置的app_offline.htm处理逻辑——即使根目录存在app_offline.htm,你的重写规则还是会把符合条件的请求转发到index.html,导致用户看不到离线页面。

要解决这个问题,只需要在你的重写规则的条件列表中,添加一个检查app_offline.htm是否存在的判断:当该文件存在时,跳过重写规则,让IIS的默认逻辑接管请求。

修改后的web.config配置如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="api/*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\server.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
      <rewrite>
        <rules>
          <rule name="React Rewrite" enabled="true" stopProcessing="true" patternSyntax="ECMAScript">
            <match url="(.*)" negate="false" />
            <conditions logicalGrouping="MatchAll">
              <!-- 新增:当app_offline.htm存在时,不执行重写 -->
              <add input="{DOCUMENT_ROOT}/app_offline.htm" matchType="IsFile" negate="true" />
              <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
              <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
              <add input="{REQUEST_URI}" pattern="(/api/)(.*)" negate="true" />
              <add input="{REQUEST_URI}" pattern="(/content/)(.*)" negate="true" />
              <add input="{REQUEST_URI}" pattern="(/static/)(.*)" negate="true" />
            </conditions>
            <action type="Rewrite" url="/index.html" />
          </rule>
        </rules>
      </rewrite>
    </system.webServer>
  </location>
</configuration>

关键说明

  • 新增的条件<add input="{DOCUMENT_ROOT}/app_offline.htm" matchType="IsFile" negate="true" />的作用是:只有当站点根目录下不存在app_offline.htm文件时,才继续执行后续的重写逻辑
  • app_offline.htm存在时,这个条件不满足,整个重写规则就会被跳过,IIS会自动返回app_offline.htm页面,同时你的API后端也会正常返回503状态码,完全符合你的预期。

另外需要确认:

  • app_offline.htm确实放置在站点的根目录下
  • IIS对该文件有读取权限

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

火山引擎 最新活动