【问题标题】:nginx + express serve static files only to authenticated usersnginx + express 仅向经过身份验证的用户提供静态文件
【发布时间】:2019-05-10 09:07:47
【问题描述】:

我正在开发一个使用 gatsby 构建的静态网站。

我希望只有知道密码的访问者才能访问它,而我不能使用 .htaccess 来访问它,因为我想要我自己的自定义“登录”页面,而不仅仅是一些浏览器的弹出窗口。

我想我会用以下端点构建一个非常简单的快速 API:

"/" - serves the static files (gatsby build files, the actual website), 
if you dont have a certain cookie, you get redirected to "/login"

GET "/login" - my custom login page (simple input for the password)

POST "/login" - in here you send the password, if its correct, 
you get the cookie and you get redirected to "/" so to the actual website

一切正常,但我有点担心不使用 nginx。我将很快部署应用程序(数字海洋),我试图了解通过 express 而不是 nginx 提供静态文件的性能如何降低速度。

我的问题是,我怎样才能以它的 nginx 提供文件的方式实现它,但是如果没有 cookie 然后像现在一样重定向到“/login”?

我读了很多书,通过 nginx 部分提供服务没有问题,但我在理解“check-if-cookie”流程时遇到了问题。

在 nginx 中检查 cookie(如果未找到则重定向)甚至是一种好习惯吗?或者也许我应该做些不同的事情?

感谢您的帮助。

【问题讨论】:

标签: node.js express nginx static-files nginx-reverse-proxy


【解决方案1】:
function checkAuth(req, res, next) {
    if (!checkAuth) {
        res.redirect('/login');
    } else {
        next();
    }
}

app.use('/admin/information', checkAuth, information);

执行与上述相同的概念。

【讨论】:

    最近更新 更多