1. 程式人生 > >Nginx+ lua實現http轉發請求

Nginx+ lua實現http轉發請求

最近要使用nginx+lua實現 一個需求:

    在nginx的location部分,請求時,判斷使用者是否為會員,如果是會員,則跳轉到a頁面,否則跳轉到b頁面。

     使用者服務是一個單獨的服務,具體lua指令碼實現程式碼如下:

upstream tuc_sgin {
    server 127.0.0.1:9806;
    server 127.0.0.1:9807;
}

location /tuc_sgin_proxy/ {
    add_header  Access-Control-Allow-Origin  *;
    proxy_pass http://tuc_sgin/;
}

#如果vip_status=1跳轉到id=35的頁面,否則跳轉到id=34的頁面
location /sgin_valuable/ {
    add_header Access-Control-Allow-Origin *;
    proxy_pass https://127.0.0.1:9808/test/news/spread.html?id=35;
    rewrite_by_lua  '
	 local cjson = require("cjson");
     local request_method = ngx.var.request_method
     local args = nil
     if "GET" == request_method then
	    args = ngx.req.get_uri_args()
     elseif "POST" == request_method then
	    ngx.req.read_body()
	    args = ngx.req.get_post_args()
     end
    local id = args["id"];
    if id == nil or id == "" then
        return ngx.redirect("https://127.0.0.1:9809/test/news/spread.html?id=34");
    end 

    local res = ngx.location.capture("/tuc_sgin_proxy/tuc/social? 
     serviceType=query_userextSingle", {
		    method = ngx.HTTP_GET, args = args})

    local result = cjson.decode(res.body);
    if result["error_no"] == "0" then
        local vip_status = result["data"]["vip_status"];
        if vip_status ~= "1"  then
            return ngx.redirect("https://127.0.0.1:9809/test/news/spread.html?id=34");
        end
    elseif result["error_no"] ~= "0" then
        return ngx.redirect("https://127.0.0.1:9809/test/news/spread.html?id=34");
    end
	'; 
}