Next.js 14.0.2 国际化改造后favicon无法显示问题求助
Next.js 14.0.2 国际化配置后网站图标无法显示问题
我在使用Next.js 14.0.2时,添加国际化并调整项目结构后遇到网站图标(favicon)无法显示的问题。
当前项目结构:
- app - [lang] - _components - _dictionaries - dictionaries.ts - layout.tsx - page.tsx - favicon.ico middleware.ts
将app文件夹下的通用文件移至[lang]目录后,我编写了middleware用于根据用户区域设置将根路径(/)重定向至/en或/ru:
import { match } from '@formatjs/intl-localematcher'; import Negotiator from 'negotiator'; function getLocale(request: any): string { const headers = request.headers || {}; const acceptLanguageHeader = headers['accept-language'] || 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7'; const negotiator = new Negotiator({ headers: { 'accept-language': acceptLanguageHeader } }); const languages = negotiator.languages(); const locales = ['ru', 'en']; const defaultLocale = 'ru'; return match(languages, locales, defaultLocale); } export function middleware(request: any) { const { pathname } = request.nextUrl; const locales = ['ru', 'en']; const pathnameHasLocale = locales.some( (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}` ); if (pathnameHasLocale) return; const locale = getLocale(request); request.nextUrl.pathname = `/${locale}${pathname}`; return Response.redirect(request.nextUrl); } export const config = { matcher: [ '/((?!_next).*)', ], };
现在浏览器网络面板中出现两个favicon.ico的请求:第一个localhost:3000/favicon.ico返回302 Found,第二个localhost:3000/en/favicon.ico返回404 Not Found,导致图标无法在浏览器标签页显示。
解决思路
排除favicon的重定向逻辑:
方法1:更新middleware的config.matcher,把favicon.ico加入排除列表,避免被重定向:export const config = { matcher: [ '/((?!_next|favicon.ico).*)', ], };方法2:在middleware函数中直接判断路径,如果是
/favicon.ico则跳过重定向:export function middleware(request: any) { const { pathname } = request.nextUrl; const locales = ['ru', 'en']; // 跳过favicon请求的重定向 if (pathname === '/favicon.ico') return; const pathnameHasLocale = locales.some( (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}` ); if (pathnameHasLocale) return; const locale = getLocale(request); request.nextUrl.pathname = `/${locale}${pathname}`; return Response.redirect(request.nextUrl); }通过Metadata指定favicon绝对路径:
在[lang]/layout.tsx中配置metadata,明确指定favicon的根路径,让浏览器直接请求正确的位置:export const metadata = { icons: { icon: '/favicon.ico', }, };验证文件位置与有效性:
确认favicon.ico确实放置在app根目录下,而非[lang]子目录;可以替换为一个已知有效的favicon文件测试是否能正常加载。
内容的提问来源于stack exchange,提问作者mondevyat
相关产品推荐
相关产品推荐

