Next.js 14应用部署在IIS子应用中出现404问题求助
解决Next.js 14部署到IIS子应用的404问题
1. 配置Next.js的basePath
在next.config.mjs中添加子应用路径作为basePath,确保和IIS子应用的虚拟路径一致:
/** @type {import('next').NextConfig} */ const nextConfig = { basePath: '/subapplication', // 替换为你的实际子应用路径 output: 'standalone', // 针对App Router优化部署,可选但推荐 } export default nextConfig
修改后必须重新执行npm run build,让配置生效。
2. 调整server.js的路径解析逻辑
IIS转发的请求会包含子应用前缀,需要在server.js中移除该前缀,才能匹配Next.js的内部路由:
const { createServer } = require('http') const { parse } = require('url') const next = require('next') const dev = process.env.NODE_ENV !== 'production' const port = process.env.PORT || 3010; const basePath = '/subapplication'; // 和next.config中的配置保持一致 const app = next({ dev, basePath }) const handle = app.getRequestHandler() app.prepare().then(() => { createServer((req, res) => { const parsedUrl = parse(req.url, true) let { pathname, query } = parsedUrl // 移除basePath前缀,处理子应用路径 if (pathname.startsWith(basePath)) { pathname = pathname.slice(basePath.length) || '/' } // 保持原有的路由匹配逻辑 if (pathname === '/a') { app.render(req, res, '/a', query) } else if (pathname === '/b') { app.render(req, res, '/b', query) } else { const modifiedUrl = { ...parsedUrl, pathname } handle(req, res, modifiedUrl) } }).listen(port, (err) => { if (err) throw err console.log(`> Ready on http://localhost:${port}${basePath}`) }) })
3. 修改web.config的重写规则
确保所有请求都正确转发到server.js并保留完整路径:
<configuration> <system.webServer> <rewrite> <rules> <rule name="myapp" 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="server.js/{R:1}" /> </rule> </rules> </rewrite> <iisnode node_env="production" nodeProcessCommandLine=""C:\Program Files\nodejs\node.exe"" interceptor=""%programfiles%\iisnode\interceptor.js"" /> <directoryBrowse enabled="true" /> </system.webServer> <location path="" overrideMode="Deny"> <system.webServer> <handlers> <add name="iisnode" path="server.js" verb="*" modules="iisnode" /> </handlers> </system.webServer> </location> </configuration>
额外检查项
- 确认IIS子应用的物理路径指向Next.js构建后的输出目录(如果用了
output: 'standalone',路径为.next/standalone)。 - 确保子应用目录拥有
IIS_IUSRS用户的读写权限。
内容的提问来源于stack exchange,提问作者Stewart Alan
相关产品推荐
相关产品推荐

