简体   繁体   中英

Nodejs, nginx, express - Checking if user is authenticated before serving static files doesn't work

app.get doesn't seem to get hit when running with nginx. It works locally however, without nginx. The code being effected is the following:

app.get('/', function(req, res, next){
    if (!req.isAuthenticated()){
        return res.redirect('/login');
    } else {
        app.use('/', express.static(path.join(__dirname, 'dist-restricted')));
        return next();
    }
});

The code checks if the user is authenticated using passport before sending them the restricted static files. While running nginx, the user doesn't get redirected to sign in.

Does nginx have something to do with this? and how do i solve it.

Your nginx is probably serving static files without passing through node.

For example with a configuration like this, nginx will directly read the file without using node :

location ~^\/(js|css|fonts|images|img|plugins|upload|pdf) {
      expires 1M;
      access_log off;
      add_header Cache-Control "public";
      add_header Access-Control-Allow-Origin *;
      add_header Access-Control-Allow-Methods GET;
      add_header Access-Control-Allow-Headers X-Requested-With,content-type;
      add_header Access-Control-Allow-Credentials true;
      root /mypatht/public;
    }

If nginx read directly your folder you can't do anything without editing nginx configuration.

To be sure simply put a console.log inside your app.get, if it not appears, you have to edit nginx

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