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

Next.js的getServerSideProps拦截favicon.ico请求该如何解决?

问题原因

Next.js 的动态路由优先级高于默认静态资源路由规则,当你未显式指定 favicon 绝对路径时,浏览器会自动拼接当前页面路由前缀发起图标请求,/[dynamiclocale]/favicon.ico 会命中前缀匹配的动态路由规则,触发对应页面的 getServerSideProps 执行。

可行解决方案
  • 方案1(优先推荐):将 favicon.ico 放置在项目根目录的 public 文件夹下,同时在页面的 <Head> 组件中显式指定 favicon 的绝对路径,从根源避免浏览器发起带路由前缀的图标请求。
    示例代码:

    import Head from 'next/head'
    
    function UserPage() {
      return (
        <>
          <Head>
            <link rel="icon" href="/favicon.ico" />
            {/* 其他head配置 */}
          </Head>
          {/* 页面内容 */}
        </>
      )
    }
    
  • 方案2:在 getServerSideProps 中新增静态资源请求过滤逻辑,遇到图标、静态资源类请求直接返回404。
    示例代码:

    export async function getServerSideProps(context) {
      const { req, res } = context
      // 匹配所有常见静态资源后缀
      const staticSuffixList = ['.ico', '.png', '.jpg', '.jpeg', '.svg', '.css', '.js', '.gif']
      if (staticSuffixList.some(suffix => req.url.endsWith(suffix))) {
        res.statusCode = 404
        return { notFound: true }
      }
      // 原有业务逻辑
      return {
        props: {}
      }
    }
    
  • 方案3:配置 next.config.js 重写规则,将所有带动态前缀的 favicon 请求重定向到根目录静态资源。
    示例代码:

    // next.config.js
    module.exports = {
      async rewrites() {
        return [
          {
            source: '/:dynamiclocale/favicon.ico',
            destination: '/favicon.ico',
          },
        ]
      },
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:09:01