Son Lam
Son Lam

Reputation: 1320

Filter request on proxy_pass using lua on nginx

I want to filter streaming url before to streaming server using proxy_pass of nginx with lua

My streaming server is http://localhost:8092

I want to when access to http://localhost:8080/streami1?token=mytoken it will be forward to http://localhost:8092/stream1. If you access to http://localhost:8080/streaming1?token=abc it will be show permission deny page.

It is my code on nginx configuration file:

  location ^~ /stream {
            set $flag_false "false";
            set $flag "false";
            set $flag_true 1;
            rewrite_by_lua '
                    local token = ngx.var.arg_token
                    if token == "mytoken" then
                            ngx.var.flag = ngx.var.flag_true
                    end

            ';
            # rewrite_by_lua "ngx.var.flag = ngx.var.flag_true";
            if ($flag = $flag_true) {
                    proxy_pass http://x.x.x.x:8092;
                    break;
            }
            echo "You do not have permission: $flag";
   }

But, it not pass to my streaming insteaf of it show "You do not have permission: 1" when i request with url whether http://localhost:8080/streaming1?token=mytoken. Obviously, it change flag value to 1, but it do not pass to my streaming. What is my wrong?. Please help me?

Upvotes: 1

Views: 4019

Answers (1)

xiaochen
xiaochen

Reputation: 1305

  1. The rewrite_by_lua directive always runs after the standard ngx_http_rewrite_module (if and set directives). You can use set_by_lua directive instead.
  2. The "=" and "!=" operators of if (condition) {} statement compare a variable with a string, which means $flag_true of if-condition will not be evaluated to 1.

And modified configure is as following:

    location ^~ /stream {
        set $flag_true 1;
        set_by_lua $flag '
            local token = ngx.var.arg_token
            if token == "mytoken" then
                return ngx.var.flag_true
            end
            return "false"
        ';
        if ($flag = 1) {
            proxy_pass http://x.x.x.x:8092;
            break;
        }
        echo "You do not have permission: $flag";
    }

Upvotes: 4

Related Questions