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

Next.js rewrites功能不生效,代理后图片、API路径错误如何解决?

你当前的rewrites规则无效的核心原因是Next.js的rewrites配置的source字段仅支持匹配请求的相对路径,不支持写入完整的绝对域名路径。

解决方案1:优先配置图片组件全局路径(最优方案,无需重写)

如果使用Next.js内置的next/image组件,直接在next.config.js中配置图片路径前缀即可,不需要使用rewrites:

const nextConfig = {
  // 你已配置的assetPrefix
  assetPrefix: "https://previewnext.mysite.com",
  images: {
    // 直接指定图片请求的完整路径前缀
    path: "https://previewnext.mysite.com/_next/image",
    // 按需补充你的图片源域名
    domains: ["previewnext.mysite.com"],
  },
}
module.exports = nextConfig

该配置会自动把所有next/image组件的请求路径直接指向真实域名,从根源避免路径错误。

解决方案2:修正rewrites规则写法

如果确实需要通过重写规则实现,正确的配置格式如下:

async rewrites() {
  return [
    {
      // source仅填写相对路径部分,用:path*匹配后续所有参数
      source: '/_next/image/:path*',
      // 目标路径完整拼接参数
      destination: 'https://previewnext.mysite.com/_next/image/:path*'
    },
    // 同理可以添加API请求的重写规则
    {
      source: '/api/:path*',
      destination: 'https://previewnext.mysite.com/api/:path*'
    }
  ]
}

如果需要仅匹配请求host为preview.mysite.com的请求才触发重写,可以添加host匹配规则:

async rewrites() {
  return [
    {
      source: '/_next/image/:path*',
      has: [
        {
          type: 'host',
          value: 'preview.mysite.com'
        }
      ],
      destination: 'https://previewnext.mysite.com/_next/image/:path*'
    }
  ]
}

关于rewrites不支持绝对路径source的说明

这不属于功能限制,因为Next.js的rewrites是匹配进入当前Next.js服务的请求,这类请求的路径本身只有相对路径部分,域名信息存储在请求头的host字段中,需要匹配域名时通过上述has参数指定host即可覆盖这类场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 08:39:04