React+TypeScript+Vite部署Azure后刷新页面出现404问题求助
解决Azure App Service上React+TypeScript+Vite应用刷新404问题
问题原因
React+Vite属于单页应用(SPA),前端路由在客户端浏览器中处理。首次访问时浏览器加载根路径的index.html,之后的路由跳转都是前端逻辑;但刷新页面时,浏览器会直接向服务器请求当前路径的资源,而服务器上不存在对应路径的文件,因此返回404错误。
解决方案
根据Azure App Service的运行环境(Windows/Linux),选择对应配置方式:
1. Windows环境
在项目的public目录下创建web.config文件,添加URL重写规则,将所有非静态资源的请求转发到index.html:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="SPA 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" /> <!-- 排除API路径,按需调整 --> </conditions> <action type="Rewrite" url="/index.html" /> </rule> </rules> </rewrite> </system.webServer> </configuration>
若项目存在后端API接口,需修改
pattern="^/(api)"为实际的API前缀,避免API请求被重写。
将web.config包含在部署包中,重新部署应用即可。
2. Linux环境
方式一:使用staticwebapp.config.json配置
在项目根目录创建staticwebapp.config.json文件,配置导航回退规则:
{ "routes": [ { "route": "/*", "serve": "/index.html", "statusCode": 200 } ], "navigationFallback": { "rewrite": "/index.html", "exclude": ["/images/*.{png,jpg,gif}", "/css/*", "/js/*"] <!-- 排除静态资源路径 --> } }
方式二:修改启动命令(使用serve托管静态文件)
如果部署时通过serve命令托管打包后的dist文件夹,在package.json的scripts中修改启动命令:
"scripts": { "start": "serve dist --single" }
或者在Azure门户的App Service配置中,进入配置 > 常规设置 > 启动命令,设置为:npx serve dist --single
--single参数会让serve将所有非文件/目录的请求重定向到index.html。
验证
重新部署应用后,刷新任意路由页面,确认不再出现404错误。
内容的提问来源于stack exchange,提问作者Punit kumar
相关产品推荐
相关产品推荐

