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

Next.js 13多语言网站图片公共路径配置问题求助

Next.js 13 多语言网站图片重定向问题解决

你的问题出在当前middleware的匹配规则上——它会处理所有非_next的请求,包括图片这类静态资源,导致图片路径被强行加上locale前缀,而实际静态资源并不存放在带locale的目录里,自然无法加载。下面是具体的修复方案:

核心修改点

  1. 调整matcher规则,排除静态资源路径,让middleware只处理页面路由
  2. 修复getLocale函数中硬编码请求头的错误,确保正确获取用户浏览器的语言偏好

修改后的完整代码

import { NextRequest, NextResponse } from "next/server";
import { match } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";

export let locales = ["nl", "fr", "en", "de"];
export let defaultLocale = "nl";

function getLocale(request: NextRequest) {
  // 从真实请求头获取Accept-Language,替代硬编码值
  const acceptLanguage = request.headers.get("accept-language") || "";
  const headers = { "accept-language": acceptLanguage };
  const languages = new Negotiator({ headers }).languages();

  return match(languages, locales, defaultLocale);
}

export function middleware(request: NextRequest) {
  const pathname = request.nextUrl.pathname;
  const pathnameIsMissingLocale = locales.every(
    (locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
  );

  if (pathnameIsMissingLocale) {
    const locale = getLocale(request);
    // 避免根路径重定向时出现重复斜杠的问题
    return NextResponse.redirect(
      new URL(`/${locale}${pathname.startsWith("/") ? "" : "/"}${pathname}`, request.url)
    );
  }
}

export const config = {
  matcher: [
    // 排除_next、静态资源路径,仅处理页面路由
    "/((?!_next|images|favicon.ico|robots.txt).*)",
  ],
};

规则说明

  • 如果你还有其他静态资源目录(比如assets、uploads),直接在matcher的排除列表里用|分隔添加即可,例如:/((?!_next|images|assets|uploads|favicon.ico).*)
  • 修复后的getLocale函数会根据用户浏览器的语言设置自动匹配最合适的locale,而不是强制使用硬编码的荷兰语
  • 重定向逻辑优化了路径拼接,避免出现/nl//这类错误格式的URL

内容的提问来源于stack exchange,提问作者Willem Beké

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 01:12:19