Prevent direct access to directory in Node & Express app

∥☆過路亽.° 提交于 2021-01-20 12:09:05

问题


In my express app i have a directory called media in /public, and i want to restrict access to it (and it's sub-directories as well), redirect or display a 404.

How i can achieve it? Thanks in advance.


回答1:


If you defined public folder in express.static middleware like this:

app.use(express.static('public'))

all public's content will be public and accessible by url /filepath/filename.

The easiest way to restrict access to media folder move media folder outside public folder.




回答2:


I figured out the answer to my own question.

app.all('/media/*', (req,res, next) {
    res.status(403).send({
       message: 'Access Forbidden'
    });
    // or whatever
});
app.use('/media',express.static(path.join(__dirname, 'media')));


来源:https://stackoverflow.com/questions/49580719/prevent-direct-access-to-directory-in-node-express-app

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!