首页 > 解决方案 > Express serves static files that are not in root directory

问题描述

I have a website with a lot of HD videos so I want to put the videos files outside of web root directory.

Here is my web root directory:

/var/node/myapp

For some basic static files like javascript, css... I put them in public directory.

/var/node/myapp/public

For video files I want to put here

/hdd/videos

This is my current serve static code:

app.use(serveStatic(path.join(__dirname, 'public'), {
    maxAge: keys.conf.maxAge,
    etag: true,
    setHeaders: setCustomCacheControl
  }));
  function setCustomCacheControl (res, path) {
    if (serveStatic.mime.lookup(path) === 'text/html') {
    res.setHeader('Cache-Control', 'public, max-age=0')
  }
}

标签: javascriptnode.jsexpress

解决方案


您可以设置多个静态目录。例子:

app.use(express.static('public', {etag: true, maxAge: keys.conf.maxAge}));
app.use(express.static('/hdd/videos'));

但是,您提供给 express.static 函数的路径是相对于您启动节点进程的目录的。如果您从另一个目录运行 express 应用程序,则使用您要服务的目录的绝对路径会更安全。

快速静态文件的文档在这里


推荐阅读