React Router 在 Azure Linux Web 应用程序上抛出 404

0 azure reactjs react-router azure-web-app-service

我们正在将 React Web App 从 Windows 应用服务迁移到 Linux 应用服务。我们有一个自定义 web.config 来处理路由,这样当用户手动访问我们的路由之一时,他们就不会遇到 404。此修复不适用于 Linux 应用服务。

我们遇到了 404,我们需要它来工作,因为我们有用户应该能够到达的自定义路由。如果他们路由到默认的 index.html,该站点就可以工作,但自定义路由则不行。我们已尝试创建新的 Windows 应用服务,迁移工作正常。关于如何让自定义路由在 Linux 应用服务中工作的任何想法?

这是我们当前使用的 web.config:

<?xml version="1.0"?>
<configuration>
 <system.webServer>
 <staticContent>
 <remove fileExtension=".woff" />
 <remove fileExtension=".woff2" />
 <remove fileExtension=".otf" />
 <remove fileExtension=".ttf" />
 <remove fileExtension=".eot" />
 <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
 <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
 <mimeMap fileExtension=".otf" mimeType="application/font-otf" />
 <mimeMap fileExtension=".ttf" mimeType="application/font-ttf" />
 <mimeMap fileExtension=".eot" mimeType="application/font-eot" />
 <clientCache cacheControlMode="DisableCache" />
 </staticContent>
 <rewrite>
 <rules>
 <rule name="React Routes" stopProcessing="true">
 <match url=".*" />
 <conditions logicalGrouping="MatchAll">
 <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
 <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
 <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
 </conditions>
 <action type="Rewrite" url="/" />
 </rule>
 </rules>
 </rewrite>
 </system.webServer>
</configuration>
Run Code Online (Sandbox Code Playgroud)

Lut*_*lho 6

正如web.config@PeterPan 已经说过的那样,当您在 Linux 应用服务中运行您的应用程序时,您不需要文件,因为它仅由 IIS 使用。

要在Azure Linux Web App Service 中运行您的 React Web 应用程序,并使对自定义路由的任何直接访问都由 index.html 处理,您需要在“设置>常规设置>启动命令”上配置启动命令,如下例所示。请记住将路径更改为您的构建路径。

pm2 serve /home/site/wwwroot/build --no-daemon --spa
Run Code Online (Sandbox Code Playgroud)

使用--spa选项 pm2 将自动将所有查询重定向到 index.html,然后反应路由器将发挥其魔力。

您可以在 pm2 文档中找到有关它的更多信息:https ://pm2.keymetrics.io/docs/usage/pm2-doc-single-page/#serving-spa-redirect-all-to-indexhtml

我最近解决了同样的问题:React router direct links not working on Azure Web App Linux