I'm using Nuxt 3 to create an SSR project.
I'm thinking of adding the Cache-Control
header to the generated static files in the .output/_nuxt
directory.
I tried the following code server/middleware/cache-control.ts
export default defineEventHandler((event) => { let res = event.res const year = 31536000 const tenmin = 600 const url = event.req.url const maxage = url.match(/(.+).(jpg|jpeg|gif|css|png|js|ico|svg|mjs)/) ? year : tenmin res.setHeader('Cache-Control', `max-age=${maxage} s-maxage=${maxage}`); })
But, it doesn't work.
How to add Cache-Control
to the generated static files?
P粉1240704512023-11-06 00:30:22
For Nuxt3, I use it as server middleware server/middleware/cache-control.js
export default defineEventHandler((event) => { if (process.env.NODE_ENV == "production") { const url = event.node.req.url; const maxage = url.match(/(.+)\.(jpg|jpeg|gif|png|ico|svg|css|js|mjs)/) ? 60 * 60 * 12 * 30 : 60 * 60; appendHeader( event, "Cache-Control", `max-age=${maxage} s-maxage=${maxage}` ); } else { appendHeader(event, "Cache-Control", `max-age= s-maxage=`); } });
P粉6183582602023-11-06 00:03:59
I'll figure it out myself. Adding the following code to nuxt.config.js will append cache controls to static files. thank you for your support!
export default defineNuxtConfig({ nitro: { routeRules: { "/img/**": { headers: { 'cache-control': `public,max-age=${year},s-maxage=${year}` } }, "/_nuxt/**": { headers: { 'cache-control': `public,max-age=${year},s-maxage=${year}` } }, } } })