You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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="&quot;C:\Program Files\nodejs\node.exe&quot;" interceptor="&quot;%programfiles%\iisnode\interceptor.js&quot;" />
    <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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 16:14:52