Mher Margaryan
Mher Margaryan

Reputation: 73

Prevent direct access to directory in Node & Express app

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.

Upvotes: 2

Views: 4716

Answers (2)

Mher Margaryan
Mher Margaryan

Reputation: 73

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')));

Upvotes: 1

zooblin
zooblin

Reputation: 2480

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.

Upvotes: 1

Related Questions