Angular 8项目本地ng serve正常 部署Azure生产环境后路由访问404
问题原因
Angular默认使用HTML5 PushState模式实现前端路由,本地开发时ng serve启动的内置服务器默认配置了所有请求 fallback 到index.html的规则,所以路由访问正常。部署到Azure后,服务器默认会按照访问路径去查找对应的静态文件,你访问的/video/xxx路径不存在对应的实体文件,因此直接返回404错误。
解决方案
提供三种适配Azure环境的解决方法,按需选择即可:
方法1:配置Azure应用服务web.config规则(适用于Azure App Service部署场景)
在项目src目录下新建web.config文件,写入以下配置:
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="Angular 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>
然后修改angular.json配置,在build->options->assets数组中添加配置,确保打包时web.config会被输出到dist根目录:
"assets": [ "src/favicon.ico", "src/assets", "src/web.config" ]
重新执行ng build --prod打包部署即可。
方法2:配置静态Web应用回退规则(适用于Azure Static Web Apps部署场景)
在项目根目录新建staticwebapp.config.json文件,写入以下配置:
{ "navigationFallback": { "rewrite": "/index.html", "exclude": ["/assets/*", "*.css", "*.js"] } }
打包时将该文件放到dist根目录一起部署即可。
方法3:改用Hash路由模式(无需修改服务器配置,改前端代码即可)
修改路由模块配置,启用HashLocationStrategy:
@NgModule({ imports: [RouterModule.forRoot(routes, { useHash: true })], exports: [RouterModule] }) export class AppRoutingModule { }
该方案改造成本最低,但是路由地址会自动添加#前缀,例如你的访问地址会变为https://vinchatfrontend.azurewebsites.net/#/video/fd2a1815-11b1-4060-6f68-08d96181122c,如果对URL格式无特殊要求可以优先选择该方案。
内容的提问来源于stack exchange,提问作者Alexgr79
相关产品推荐
相关产品推荐

