Nuxt 3的缓存常见的配置方式,nuxtApp.hook和defineNuxtConfig.routeRules。
nuxtApp.hook
在项目中新建plugins/cache.server.ts文件:
export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.hook('app:rendered', (ctx) => {
    const res = ctx.ssrContext?.event.node.res
    if (res) {
      const url = ctx.ssrContext?.event.node.req.url || ''
      // 根据 URL 或文件扩展名设置缓存时间
      let cacheDuration = 60 * 60 * 24 * 365 // 默认缓存 1 年(对于 HTML 等页面)
      // 判断是否为新闻详情页
      if (url.startsWith('/single/')) {
        // 这里可以提取新闻 ID 或其他动态部分
        res.setHeader('Cache-Control', 'public, max-age=3600') // 缓存 1 小时
      } else if (url.endsWith('.html')) {
        cacheDuration = 60 * 60 * 24 * 365 // HTML 文件缓存 1 年
      } else if (url.endsWith('.js') || url.endsWith('.css')) {
        cacheDuration = 60 * 60 * 24 * 30 // JavaScript 和 CSS 缓存 30 天
      } else if (
        url.endsWith('.jpg') ||
        url.endsWith('.jpeg') ||
        url.endsWith('.png') ||
        url.endsWith('.gif')
      ) {
        cacheDuration = 60 * 60 * 24 * 365 * 2 // 图片缓存 2 年
      } else if (url.endsWith('.svg') || url.endsWith('.webp')) {
        cacheDuration = 60 * 60 * 24 * 365 * 2 // SVG 和 WebP 缓存 2 年
      } else if (url.endsWith('.json')) {
        cacheDuration = 60 * 60 * 24 * 7 // JSON 文件缓存 1 周
      } else if (url.endsWith('.xml')) {
        cacheDuration = 60 * 60 * 24 * 7 // XML 文件缓存 1 周
      } else {
        cacheDuration = 60 * 60 * 24 * 7 // 默认缓存时间 1 周
      }
      // 设置 Cache-Control 头
      res.setHeader('Cache-Control', `public, max-age=${cacheDuration}`)
    }
  })
})
nuxt.config.ts的plugins引入~/plugins/cache.server.ts
  plugins: [
    {
      src: '~/plugins/cache.server.ts',
    },
  ],defineNuxtConfig.routeRules
缓存策略是由 Nitro 服务器端处理的。Nginx 会基于这些缓存规则缓存响应内容并提供给客户端,直到缓存过期。
- 用户通过浏览器(客户端)访问网站,发起 HTTP 请求。
- Nginx(反向代理)将请求转发到 Node.js 服务(如端口 8200)。
- 根据 nitro.routeRules 中的规则,服务器决定是否缓存响应数据(例如 HTML、JS、CSS、图片等)。
- 如果缓存规则生效,Nginx 或代理服务器会在请求期间缓存响应,并在缓存有效期内直接返回缓存的内容,而不重新请求 Node.js 服务器。
- 缓存过期后,Nginx 会再次请求 Node.js 服务器来获取新内容。
  routeRules: {
    '/blog/**': { cache: { maxAge: 60 * 60 } },
  },参考文档
https://nitro.build/guide/cache
https://nuxt.com/docs/api/nuxt-config#routerules-1
https://nuxt.com/docs/api/advanced/hooks#app-hooks-runtime