我正试图创建一个"只允许用户"的部分,我设法做到了这一点,但我被卡住了。
我使用Nginx和Express.js.的auth_request模块
如何将请求的url发送到我的api路由?
"/"
是通用URL,但只有当访问者试图访问文件时,才应该触发/api/:filename
,无论文件的位置/URL是什么。简而言之,我想做的是,"好吧,我是Nginx,我看到一些访问者试图访问这个文件(或多个文件,它会单独检查)。让我们把这个文件的名称传递给Express.js服务器,让它检查这个用户是否被允许看到这个图像。如果它说200,我会允许。如果它是403,那就不允许。"
app.get('/api/:filename', function(req,res,next) {
// This part decides what you're allowed to see.
// Redis database query. Returns 0 or 1.
// 1 means 200, 0 means 403.
res.sendStatus(200);
// It works if I omit :filename part, so this part is done in theory,
// but we didn't get the file name, so right now all we have is "yes
// to all" or "no to all", it's not dynamic.
});
问题是,我不知道如何将请求的url参数从Nginx传递到我的Express.js应用程序(例如image.jpg
、video.mp4
,格式为http://localhost/api/:filename
),这样我就可以根据数据库检查用户的权限,并为每个文件返回动态响应。
这是我的Nginx配置。
upstream localhost {
ip_hash;
server 127.0.0.1:8000;
server 127.0.0.1:8001;
server 127.0.0.1:8002;
server 127.0.0.1:8003;
}
server {
listen 80;
server_name localhost;
location ~* ^.+.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf)$ {
root images;
auth_request /api; // How to append requested filename to this URL?
}
location / {
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_http_version 1.1;
proxy_pass http://localhost;
}
}
编辑1
location = /api {
proxy_pass http://localhost;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-URI $request_uri;
}
为"/api"定义一个自定义位置,并将/api$request_uri(原始uri)附加到proxy_pass;
location = /api {
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_http_version 1.1;
proxy_pass http://localhost/api$request_uri;
}