Kob_24
Kob_24

Reputation: 612

Deny access to specific directory in nodejs express

I am trying to deny public to see files in a special directory using node express following is the code:

app.use(express.static(path.join(__dirname, 'partials')));

app.all('/partials/*', function (req,res, next) {

    res.status(403).send(
    {
        message: 'Access Forbidden'
    });
    next();
});

If i route to localhost/partials, i get the message 'Access Forbidden' But not if i route to localhost/partials/files.html

Any recommendations?

Upvotes: 5

Views: 5021

Answers (1)

Mukesh Sharma
Mukesh Sharma

Reputation: 9022

Order of statements matter in node.js.

app.all('/partials/*', function (req,res, next) {
   res.status(403).send({
      message: 'Access Forbidden'
   });
});

//this line is used to load resources at localhost/partials/api.html
//but, because of above code snippets, we have blocked /partials/* routes
//hence, this line will practically wont work.
app.use('/partials',express.static(path.join(__dirname, 'partials')));

Upvotes: 7

Related Questions