简体   繁体   English

Node.js,nginx,Express-在提供静态文件之前检查用户是否已通过身份验证

[英]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. 使用nginx运行时,app.get似乎没有受到攻击。 It works locally however, without nginx. 但是,它在本地运行,没有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. 运行nginx时,不会重定向用户登录。

Does nginx have something to do with this? Nginx是否与此有关? and how do i solve it. 以及我该如何解决。

Your nginx is probably serving static files without passing through node. 您的nginx可能在不通过节点的情况下提供静态文件。

For example with a configuration like this, nginx will directly read the file without using node : 例如,使用这样的配置,nginx将直接读取文件,而无需使用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. 如果nginx直接读取您的文件夹,则不编辑nginx配置就无法做任何事情。

To be sure simply put a console.log inside your app.get, if it not appears, you have to edit nginx 要确保将console.log放入app.get内,如果未出现,则必须编辑nginx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM