Nginx - OpenResty簡易實現nginx的token驗證和動態跳轉
阿新 • • 發佈:2021-12-20
OpenResty簡易實現nginx的token驗證和動態跳轉
首先在電腦上搭建OpenResty環境:https://www.cnblogs.com/helios-fz/p/15703260.html
然後建立一個 test.lua 檔案:
-- 獲取請求頭 local headers = ngx.req.get_headers() -- 獲得請求頭中的 token 引數 local token = headers["token"] if token then -- 這裡連線了本地redis,如果有密碼,需要加上 -a 引數 local cmd = "redis-cli -h 127.0.0.1 -p 6379 -n 0 get"..token local f = io.popen(cmd) res = tostring(f:read()) f:close() -- 這裡判斷 redis 中是否存在 token if res ~= " " then -- 在這裡可以加一些複雜邏輯 return "http://www.baidu.com" else return "https://www.cnblogs.com/helios-fz/" end else return "https://www.cnblogs.com/helios-fz/" end
在 nginx.conf 檔案中加入配置:
server { listen 8005; server_name localhost; location / { resolver 8.8.8.8; set_by_lua_file $full_proxy_pass 你檔案的絕對路徑/test.lua; proxy_set_header Host $proxy_host; proxy_pass $full_proxy_pass; } }
這裡有兩個關鍵配置,如果不加上,跳轉的時候就會報404錯誤
關鍵配置一
proxy_set_header Host $proxy_host;
語法 | proxy_set_headerfield value ; |
預設值 |
proxy_set_header Host $proxy_host; proxy_set_header Connection close; |
上下文 | http, server, location |
proxy_set_header 允許重新定義或者添加發往後端伺服器的請求頭。
value可以包含文字、變數或者它們的組合。
當且僅當當前配置級別中沒有定義proxy_set_header指令時,會從上面的級別繼承配置。 預設情況下,只有兩個請求頭會被重新定義:
proxy_set_header Host $proxy_host;
proxy_set_header Connection close;
所以上述 nginx.conf 如果不重新定義proxy_set_header Host 的話,那麼預設 Host 值就還是當前訪問路徑的 Host 資訊。
關鍵配置二
resolver 8.8.8.8;
官方解釋如下:
Configures name servers used to resolve names of upstream servers into addresses
反向代理的場景下,upstream後端用域名時,配置resolver以便於nginx能夠解析該域名。
平時我們在配置NG upstream 時,一般都是指定 IP 地址或者是地址池,或者是一個固定的域名。
但一些複雜的場景,比如我們的 upstream 是變數的 servername,這時候需要用到resolver 的指令用來對變數做解析了。