用Lua控制Nginx靜態文件的url訪問權限


需求背景:比如我們有一個存儲文件的web服務器,一般通過url可直接訪問到:http://127.0.0.1/uploads/test.rar,如果我們需要限制別人的訪問,可以通過添加lua腳本來控制url訪問權限,以下是實現步驟。

安裝LuaJIT

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

tar zxf LuaJIT-2.1.0-beta2.tar.gz
cd LuaJIT-2.1.0-beta2
make PREFIX=/usr/local/luajit
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

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

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

重新編譯安裝Nginx

nginx -V查看已經編譯的配置

nginx -V

輸出結果:

--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解壓路徑)

--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

完整編譯配置如下:

# 設置環境變量
export LUAJIT_LIB=/usr/local/luajit/lib
export LUAJIT_INC=/usr/local/luajit/include/luajit-2.1
# 配置
./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
# 編譯安裝
make -j2
make install

配置Nginx.conf

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

location ^~ /uploads/ {
            access_by_lua '
                local secret_key = "prefix_eu56#42dfd6g*@"
                local diff_time  = 10
                local local_time = ngx.time()
                local timestamp = tonumber(ngx.var.arg_timestamp)
                local token     = ngx.var.arg_token

                if (timestamp == nil or token == nil) then
                    ngx.exit(403)
                elseif (timestamp + diff_time < local_time) then
                    ngx.exit(403)
                end

                local access_token = ngx.md5(timestamp..secret_key)

                if token == access_token then
                    return true
                else
                    ngx.exit(403)
                end
            ';
        }

重啟Nginx

service nginx restart

檢查生效狀態

訪問URL:http://127.0.0.1/uploads/test.rar?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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM