Nginx:基于 LUA Redis 阻止内容 URL(.MP4 或 .PNG)

Nginx: Block Content URL (.MP4 or .PNG) based on LUA Redis

如果用户不在会话中,我想阻止对某些内容(例如视频和图像)的访问。 为了检查它是否经过身份验证,我在后端使用它(通过 redis):hset users token123 on

示例 URL 请求:./content/s04-40dm4-de2020.mp4?token=token123

如果"token123"是"on",我想通过lua-resty-redis模块检查,如果nginx不去"block"请求,如果它通常会被允许。 我不知道如何在不损失很多性能的情况下做到这一点,我目前正在将 redis 模块与此混合使用:

content_by_lua '
    ... (Check in lua-resty-redis equals "on")
     local file = "/ path ..."
     local f = io.open (file, "rb")
     local content = f: read ("* all")
     f: close ()
     ngx.print (content)
';

有没有一种方法可以仅在您未通过身份验证且未执行上述操作时阻止? 注意:在 nginx 中的位置:"location ~* ^.+.(jpeg|gif|png|jpg|mp4|...etc)"

使用 NGINX auth_request 来处理令牌的验证。

http://nginx.org/en/docs/http/ngx_http_auth_request_module.html#auth_request

location /contents/ {
    auth_request /auth;
    ...
}

location = /auth {

    #Validate your token here. You can use proxy request, njs js_content or lua.

    proxy_pass ...
    proxy_pass_request_body off;
    proxy_set_header Content-Length "";
    proxy_set_header X-Original-URI $request_uri;
}