ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

使用nginx对视频、音频、图片等静态资源网址,加token签权

2026/8/15 16:13:26 拓冰建站 浏览量
使用nginx对视频、音频、图片等静态资源网址,加token签权

目前很多静态资源,都可以无权限验证,进行访问或转发,对有价值的资源进行签权,限制转发无法在代码中实现拦截,我们可以使用nginx对视频、音频、图片等静态资源网址,加token签权

如:

http://192.168.1.22/123.mp3

http://192.168.1.22/123.m3u8

http://192.168.1.22/123.flv

对这些资源想增加token进行验证,如 :

http://192.168.1.22/123.flv?token=123

 后端接口对token进行验证,通过即可以访问,不通过 跳转到其它 连接

1、下载nginx,这里是用window版本

 由于需要用到lua脚本,所以下载第三方插件版本的

 OpenResty  https://openresty.org/en/

 解压后

修改配置文件 

conf/nginx.conf

在http 中增加以下配置

    server {listen       8018;server_name  localhost;location /proxyprd {#访问验证token接口 并提交传参rewrite ^/180m7s/(.*) /$1 break;proxy_pass http://125.7.23.10:8011/LuaVideoCheck/luaVideoCheck;}	location /180m7s {#访问地址域名:端口/180m7sdefault_type text/plain;	access_by_lua '			local	myIP = ngx.req.get_headers()["X-Real-IP"]if myIP == nil thenmyIP = ngx.req.get_headers()["x_forwarded_for"]			 elseend	if myIP == nil thenmyIP = ngx.var.remote_addrendlocal tokenstr= ""local args = ngx.req.get_uri_args()for key, val in pairs(args) doif key == "token" thentokenstr=val			endendlocal urlstr = ngx.var.urilocal pos = string.find (urlstr,".st")		local posseghik = string.find (urlstr,"seghik") local posm3u8 = string.find (urlstr,".m3u8")if pos and posseghik then	if  not posm3u8 then		ngx.exec("@180m7sUrl")returnendendlocal res = ngx.location.capture("/proxyprd", {args={token=tokenstr, ip=myIP,url=urlstr,sysname="proxyprd"}})   #如果接口luaVideoCheck验证token通过返回1,转发原始视频流内容if res.body=="1" thenngx.exec("@180m7sUrl")returnendif res.body=="-1" then#如果接口luaVideoCheck验证token不通过返回-1,转发空内容returnendreturn	 	        
';		}location @180m7sUrl{#视频原始访问域名端口#local urlstr = ngx.var.uri#local urlstr=ngx.req.get_headers()["User-Agent"]rewrite /180m7s/(.*) /$1 break;proxy_pass  http://59.5.36.80:6060;}error_page   500 502 503 504  /50x.html;location = /50x.html {root   html;}}

在你的接口http://xxx.xxx.xx...xx/LuaVideoCheck/luaVideoCheck 中添加验证程序

 public int luaVideoCheck(string ip = "", string token = "", string url = "", string sysname = ""){if(token=="123"){return 1;}else{return -1;}}

保存配置

运行程序

测试步骤:

1、请求:http://nginx服务器的ip:8018/147m7s/123.flv?token=123

2、接口自动验证token:http://xxx.xxx.xx...xx/LuaVideoCheck/luaVideoCheck

3、验证通过,内容请求会自动转发到 http://59.5.36.80:6060/123.flv