How to add cache control in generated static files (Nuxt 3)
P粉765684602
P粉765684602 2023-11-05 08:55:14
0
2
610

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?

P粉765684602
P粉765684602

reply all (2)
P粉124070451

For Nuxt3, I use it as server middlewareserver/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粉618358260

    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}` } }, } } })
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!