[关闭]
@dume2007 2017-02-24T03:49:47.000000Z 字数 2179 阅读 2933

用Lua控制Nginx静态文件的权限访问

lua nginx


安装LuaJIT

下载地址:http://luajit.org/download.html

  1. tar zxf LuaJIT-2.1.0-beta2.tar.gz
  2. cd LuaJIT-2.1.0-beta2
  3. make PREFIX=/usr/local/luajit
  4. make install PREFIX=/usr/local/luajit

下载ngx_devel_kit模块

下载地址:https://github.com/simpl/ngx_devel_kit/tags
目前最新版本:https://github.com/simpl/ngx_devel_kit/archive/v0.3.0.tar.gz

  1. tar -xzvf v0.3.0.tar.gz # 不需要安装

下载lua-nginx-module模块

下载地址:https://github.com/openresty/lua-nginx-module/tags
目前最新版本:https://github.com/openresty/lua-nginx-module/archive/v0.10.7.tar.gz

  1. tar -xzvf v0.10.7.tar.gz # 不需要安装

重新编译安装Nginx

nginx -V查看已经编译的配置

  1. nginx -V

输出结果:

  1. --user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_v2_module --with-http_gzip_static_module --with-ipv6 --with-http_sub_module

进入Nginx源码目录,重新编译,加上以下参数(注意以下module解压路径)

  1. --with-ld-opt=-Wl,-rpath,/usr/local/luajit/lib --add-module=/path/to/ngx_devel_kit-0.3.0 --add-module=/path/to/lua-nginx-module-0.10.7

完整编译配置如下:

  1. # 设置环境变量
  2. export LUAJIT_LIB=/usr/local/luajit/lib
  3. export LUAJIT_INC=/usr/local/luajit/include/luajit-2.1
  4. # 配置
  5. ./configure --user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_v2_module --with-http_gzip_static_module --with-ipv6 --with-http_sub_module --with-ld-opt=-Wl,-rpath,/usr/local/luajit/lib --add-module=/home/vagrant/ngx_devel_kit-0.3.0 --add-module=/home/vagrant/lua-nginx-module-0.10.7
  6. # 编译安装
  7. make -j2
  8. make install

配置Nginx.conf

在在/usr/local/nginx/conf/nginx.conf中的server节加入如下代码:

  1. location ^~ /uploads/ {
  2. access_by_lua '
  3. local secret_key = "xhh_eu56#42dfd6g*@"
  4. local diff_time = 10
  5. local local_time = ngx.time()
  6. local timestamp = tonumber(ngx.var.arg_timestamp)
  7. local token = ngx.var.arg_token
  8. if (timestamp == nil or token == nil) then
  9. ngx.exit(403)
  10. elseif (timestamp + diff_time < local_time) then
  11. ngx.exit(403)
  12. end
  13. local access_token = ngx.md5(timestamp..secret_key)
  14. if token == access_token then
  15. return true
  16. else
  17. ngx.exit(403)
  18. end
  19. ';
  20. }

重启Nginx

  1. service nginx restart

检查生效状态

访问URL:http://10.15.168.25/uploads/test.png?token=52f0b2b4ebedb0094eff53383098a4b8&timestamp=1487901531

权限判断规则:

1、URL必须包含timestamp和token参数
2、timestamp为秒级时间戳,10s之内时间有效
3、token为md5(timestamp+secret_key)

时间过期输出403 Forbidden
验证成功返回文件。

文档资料

Nginx API for Lua:
https://github.com/openresty/lua-nginx-module#nginx-api-for-lua

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注