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

如何为NextJS 13 App目录电商应用配置CloudFlare/CloudFront CDN

解决NextJS 13 App Router区分静态/动态页面CDN缓存策略的方案

一、静态页面(商品页、关于我们等)设置长期缓存

在App Router中,可通过页面组件或布局的headers函数直接配置Cache-Control,让CDN识别并缓存静态内容:

1. 单个静态页面独立设置

在对应页面的page.tsx中添加headers函数,匹配目标路由并设置缓存规则:

export async function headers() {
  return [
    {
      source: '/products/:slug', // 匹配商品页动态路由,按实际路由调整
      headers: [
        {
          key: 'Cache-Control',
          value: 'public, max-age=86400, s-maxage=604800, stale-while-revalidate=86400',
        },
      ],
    },
    {
      source: '/about', // 关于我们页面
      headers: [
        {
          key: 'Cache-Control',
          value: 'public, max-age=86400, s-maxage=604800, stale-while-revalidate=86400',
        },
      ],
    },
    {
      source: '/contact', // 联系我们页面
      headers: [
        {
          key: 'Cache-Control',
          value: 'public, max-age=86400, s-maxage=604800, stale-while-revalidate=86400',
        },
      ],
    },
  ];
}
  • public:允许CDN与浏览器缓存内容
  • max-age=86400:浏览器缓存1天
  • s-maxage=604800:CDN缓存7天
  • stale-while-revalidate:允许CDN返回过期缓存的同时,后台异步更新最新内容

2. 全局静态布局统一配置

若多个静态页面共享同一布局,可在布局文件中设置headers避免重复代码:

// app/layouts/static-layout.tsx
export async function headers() {
  return [
    {
      source: '/(products|about|contact)/:path*', // 批量匹配所有静态页面路由
      headers: [
        {
          key: 'Cache-Control',
          value: 'public, max-age=86400, s-maxage=604800, stale-while-revalidate=86400',
        },
      ],
    },
  ];
}

二、动态页面(用户资料、购物车等)设置禁止缓存

对于需要实时获取数据的动态页面,需配置强制跳过缓存的规则,确保请求直接到达源服务器:

1. 单个动态页面独立设置

在对应页面的page.tsx中添加headers函数:

// app/profile/page.tsx
export async function headers() {
  return [
    {
      source: '/profile/:userId', // 用户资料动态路由
      headers: [
        {
          key: 'Cache-Control',
          value: 'no-store, no-cache, must-revalidate, proxy-revalidate',
        },
        {
          key: 'Pragma',
          value: 'no-cache',
        },
        {
          key: 'Expires',
          value: '0',
        },
      ],
    },
    {
      source: '/cart', // 购物车页面
      headers: [
        {
          key: 'Cache-Control',
          value: 'no-store, no-cache, must-revalidate, proxy-revalidate',
        },
      ],
    },
  ];
}
  • no-store:完全禁止缓存,每次请求必须从源服务器获取
  • proxy-revalidate:强制CDN向源服务器验证,杜绝CDN缓存动态内容

2. 中间件批量处理动态路由

若存在大量动态页面,可通过middleware.ts按路由规则统一设置缓存头:

// app/middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const response = NextResponse.next();

  // 匹配所有动态页面路由
  const isDynamicRoute = request.nextUrl.pathname.startsWith('/profile') || request.nextUrl.pathname.startsWith('/cart');
  
  if (isDynamicRoute) {
    response.headers.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
    response.headers.set('Pragma', 'no-cache');
    response.headers.set('Expires', '0');
  } else {
    // 非动态页面默认应用静态缓存规则
    response.headers.set('Cache-Control', 'public, max-age=86400, s-maxage=604800, stale-while-revalidate=86400');
  }

  return response;
}

// 指定中间件生效范围,排除API、静态资源等无需处理的路径
export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};

三、验证缓存规则生效情况

部署后,通过浏览器开发者工具的Network面板查看页面的Response Headers:

  • 静态页面应显示public, max-age=86400, s-maxage=604800, stale-while-revalidate=86400
  • 动态页面应显示no-store, no-cache, must-revalidate, proxy-revalidate

CDN(CloudFlare/CloudFront)会自动遵循这些响应头的缓存规则,无需在CDN面板额外配置路由规则,实现NextJS层面统一管理缓存策略。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 17:22:51