简体   繁体   中英

Serving static files in Node app from maxCDN

Currently we have existing project created with keystone + nunjucks, and all paths to static files looks like /stc/img/someimage.jpg , so I don't want to change the links in template. Is it any way to serve them through middleware in node server from maxCDN? something like:

app.use((req, res, next) => {
  if (
    req.path.slice(-5) === '.jpeg' ||
    req.path.slice(-4) === '.jpg' ||
    req.path.slice(-4) === '.svg' ||
    req.path.slice(-4) === '.png' ||
    req.path.slice(-4) === '.gif' ||
    req.path.slice(-4) === '.css' ||
    req.path.slice(-3) === '.js'
  ) {
    req.path = `https://domain.cdn-ssl.com${req.path}`;
  }
  next();
});

Simple way is redirect:

app.use((req, res, next) => {
  if (
    req.path.slice(-5) === '.jpeg' ||
    req.path.slice(-4) === '.jpg' ||
    req.path.slice(-4) === '.svg' ||
    req.path.slice(-4) === '.png' ||
    req.path.slice(-4) === '.gif' ||
    req.path.slice(-4) === '.css' ||
    req.path.slice(-3) === '.js'
  ) {
    res.redirect( `https://domain.cdn-ssl.com${req.path}` );
  } else {
      next();
  }
});

Or you can use middleware like express-http-proxy - https://www.npmjs.com/package/express-http-proxy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM