Next.js部署Azure App Service后直接访问路由报404,开发环境正常
解决Azure App Service中Next.js直接访问路由404问题
问题根源
你的Next.js应用是纯客户端渲染(CSR),所有路由逻辑都在浏览器端处理。Azure App Service默认使用IIS作为Web服务器,当直接访问/vehicle-details这类路由时,IIS会尝试在服务器文件系统中寻找对应的物理文件或目录,找不到就返回404。而通过Link或router.push的内部导航是在客户端通过JS切换路由,不会触发新的服务器请求,所以能正常工作。
解决方案
1. 添加web.config重写规则(推荐)
在项目根目录创建web.config文件,让IIS将所有非物理文件/目录的请求转发到index.html,由Next.js客户端路由接管:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="Next.js 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> <staticContent> <mimeMap fileExtension=".json" mimeType="application/json" /> </staticContent> </system.webServer> </configuration>
部署时将这个文件一起上传到Azure App Service即可。
2. 调整Next.js的trailingSlash配置
如果业务允许路由带尾斜杠,可以修改next.config.js中的trailingSlash为true:
module.exports = withTM({ // 保留其他原有配置 trailingSlash: true, // 保留其他原有配置 })
开启后路由会变为/vehicle-details/,Azure App Service会默认处理这类带尾斜杠的路径,配合Next.js的静态资源逻辑解决404,但会改变路由格式,需根据需求选择。
3. 适配output: 'standalone'模式
你当前配置了output: 'standalone',这种模式下Next.js会生成独立的Node.js服务器。需要确保Azure App Service的启动命令正确:
- 部署后,服务器入口文件为
.next/standalone/server.js - 在Azure App Service的「配置」→「常规设置」中,设置启动命令为:
node .next/standalone/server.js
这种方式下,Next.js自带的服务器会处理所有路由请求,无需依赖IIS重写规则。
最佳实践
- 纯CSR应用优先使用
web.config重写规则,无需修改路由格式,适配性最强 - 使用
standalone模式部署时,必须配置正确的启动命令,让Next.js自身服务器处理请求 - 开发环境正常是因为
next dev自带的开发服务器会自动处理路由转发,生产环境部署到Azure后需要额外配置适配服务器
内容的提问来源于stack exchange,提问作者Gabriel Oliveira Menezes
相关产品推荐
相关产品推荐

