I'm using Nuxt 3 to create an SSR project. I'm thinking of adding theCache-Controlheader to the generated static files in the.output/_nuxtdirectory.
I tried the following codeserver/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 addCache-Controlto the generated static files?
For Nuxt3, I use it as server middleware
server/middleware/cache-control.jsexport 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=`); } });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}` } }, } } })