Nginx - OpenResty簡易實現nginx的token驗證和動態跳轉


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_header field 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 的指令用來對變量做解析了。


免責聲明!

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



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