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

Next.js 13部署Vercel预发布环境后_next/image无法显示如何阻止重定向?

问题

我配置的Next.js middleware.ts 文件如下:

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     * - fonts (font files)
     */
    '/((?!_next/image|_next/static|api|favicon.ico|fonts).*)',
   ],
};

本地环境下的优化图片URL为 http://localhost:3000/_next/image?url=,部署到Vercel预发布环境后对应的URL是 https://{vercel_stage_server_domain}/_next/image?url=。本地运行一切正常,但预发布环境中图片请求出现重定向问题,无法正常显示。请问该如何阻止这个重定向?


解决方案

1. 强制放行图片优化请求

在middleware逻辑最顶部添加判断,直接跳过对_next/image路径请求的处理,避免被其他重定向逻辑干扰:

import { NextRequest, NextResponse } from 'next/server';

export function middleware(request: NextRequest) {
  // 直接放行图片优化服务的请求
  if (request.nextUrl.pathname.startsWith('/_next/image')) {
    return NextResponse.next();
  }

  // 你的其他路由重定向、权限校验等逻辑
}

export const config = {
  matcher: [
    '/((?!_next/image|_next/static|api|favicon.ico|fonts).*)',
  ],
};

2. 修正Matcher规则的精确性

Vercel预发布环境的请求路由可能存在隐性前缀或解析差异,可优化matcher规则的正则写法,确保_next/image路径被彻底排除:

export const config = {
  matcher: [
    // 更紧凑的正则写法,确保_next/image和_next/static被完全排除
    '/((?!_next/(image|static)|api|favicon.ico|fonts).*)',
  ],
};

3. 排查图片域名配置

如果上述方法无效,检查next.config.js中的图片域名配置:

  • 若使用外部图片源,需确保images.remotePatterns或images.domains已正确配置允许对应域名,否则Vercel图片优化服务会返回重定向错误(并非middleware导致,但表现为图片无法加载):
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'your-image-domain.com',
      },
    ],
    // 或使用domains(适用于旧版Next.js)
    // domains: ['your-image-domain.com'],
  },
};

module.exports = nextConfig;

4. 对齐本地与预发布环境的Next.js版本

确保Vercel预发布环境使用的Next.js版本和本地开发环境完全一致,版本差异可能导致路由匹配逻辑出现偏差。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 01:17:36