nginx proxy_pass based on whether request method is POST, PUT or DELETE

后端 未结 4 830
春和景丽
春和景丽 2020-12-23 10:36

I have two iKaaro instances running on port 8080 and 9080, where the 9080 instance is Read only.

I am unsure how to use nginx for example if the request method is PO

4条回答
  •  既然无缘
    2020-12-23 11:21

    I assume you got the basics in place. I.E., you have installed Lua 5.1, or better still, LuaJIT 2.0, on your server, compiled Nginx with the ngx_lua module and configured ngx_lua as required.

    With that in place, This will do the job:

    location /test {
        content_by_lua '
            local reqType = ngx.var.request_method
            if reqType == ngx.HTTP_POST 
                OR reqType == ngx.HTTP_DELETE 
                OR reqType == ngx.HTTP_PUT 
            then
                res = ngx.location.capture("/write_instance")
            else
                res = ngx.location.capture("/read_instance")
            end
            ngx.say(res.body)
        ';
    }
    location /write_instance {
        internal;
        proxy_pass http://127.0.0.1:8080;
    }
    location /read_instance {
        internal;
        proxy_pass http://127.0.0.1:9080;
    }
    

    UPDATE

    I thought perhaps you were specifically using Lua in a larger scope. The example below would also work on the same principle as limit_except.

    location /test {
        if ($request_method !~* GET) {
            # For Write Requests
            proxy_pass http://127.0.0.1:8080;
        }
        # For Read Requests
        proxy_pass http://127.0.0.1:9080;
    }
    

    Both "if" and "limit_except" block effectively create a nested location block and once the condition matches, only the content handler ("proxy_pass") of the inner location block thus created will be executed.

    Not fully getting this is why if is sometimes said to be "evil" but in this case the "evil" behaviour, common to both "if" and "limit_except", may be exactly what you want.

    So three choices for you to pick from!

    Note however that you will have to watch that you don't get bitten by the "evil" behaviour with either of the "if" or "limit_except" options if you need to set any other directives.

    I.E., if you set a directive inside the "if" or "limit_except" block, it may not be active outside it and similarly, something set outside may be inherited inside. So you have to watch how defaults are inherited, or not, as the case may be, with both approaches.

    All the potential issues listed on the If is Evil page apply equally to "if" and "limit_except" here. The Lua based scripting approach will avoid many of those potential pitfalls as suggested on that page.

    Good luck!

提交回复
热议问题