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

Next.js结合IIS反向代理时静态资源路径问题求助

Next.js 部署到 IIS 子路径下静态资源404问题解决方案

问题根源

核心问题出在IIS反向代理规则与Next.js basePath配置不匹配,以及public资源引用未适配basePath导致的路径错误。

正确配置步骤

1. 修正Next.js配置(next.config.js)

根据环境自动配置basePath,兼顾开发与生产环境:

/** @type {import('next').NextConfig} */
const nextConfig = {
  // 生产环境启用basePath,开发环境留空
  basePath: process.env.NODE_ENV === 'production' ? '/test' : '',
  // 无需单独配置assetPrefix,basePath会自动为_next资源添加前缀
}

module.exports = nextConfig

2. 调整IIS反向代理规则

之前的规则把domain/test直接代理到localhost:4001,但Next.js启用basePath后,首页路由是localhost:4001/test,需修改URL Rewrite规则:

  • 匹配URL模式:^test/(.*)
  • 重写URL:http://localhost:4001/test/{R:1}
  • 勾选「Append query string」(保留查询参数)
  • 可选:添加条件{HTTP_HOST}等于你的域名,避免影响其他站点

修改后,domain/test/xxx会被正确代理到localhost:4001/test/xxx,与Next.js路由完全匹配。

3. 统一public资源引用方式

Next.js内置组件(如Image、Link)会自动带上basePath,但普通img、script标签需手动拼接路径,推荐两种方式:

方式一:环境变量判断
export default function Home() {
  const basePath = process.env.NODE_ENV === 'production' ? '/test' : ''
  return (
    <div>
      {/* Next.js Image组件自动适配basePath */}
      <Image src="/logo.png" alt="Logo" width={100} height={100} />
      {/* 普通img标签手动拼接 */}
      <img src={`${basePath}/logo.png`} alt="Logo" />
    </div>
  )
}
方式二:通过useRouter获取basePath
import { useRouter } from 'next/router'

export default function Home() {
  const router = useRouter()
  return (
    <img src={`${router.basePath}/logo.png`} alt="Logo" />
  )
}

为什么之前的配置无效?

  • 单独设置basePath时,Next.js会把所有路由和资源前缀设为/test,但你的IIS代理规则未将domain/test对应到localhost:4001/test,导致需访问domain/test/test才能命中首页。
  • 单独设置assetPrefix仅能覆盖_next文件夹下的编译资源,public文件夹的资源是手动编写的绝对路径,不会自动添加前缀,因此仍请求根域名。

内容的提问来源于stack exchange,提问作者DreamyPac

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 13:33:45