nginx proxy_pass基于请求方法是POST,PUT还是DELETE

问题描述 投票:21回答:4

我在端口8080和9080上运行了两个iKaaro实例,其中9080实例是只读的。

我不确定如何使用nginx例如,如果请求方法是POST,PUT,DELETE然后发送到写实例(8080),否则发送到9080实例。

我使用正则表达式使用位置做了一些事情,但这不正确。

http://wiki.nginx.org/HttpLuaModule我看到有可以调用的'HTTP方法常量',所以添加位置块是正确的:

location ~* "(ngx.HTTP_POST|ngx.HTTP_DELETE|ngx.HTTP_PUT)" {
    proxy_pass http://127.0.0.1:8080;

谢谢

lua nginx
4个回答
35
投票

我刚做了一个快速测试,这对我有用:

server {
  location / {
    # This proxy_pass is used for requests that don't
    # match the limit_except
    proxy_pass http://127.0.0.1:8080;

    limit_except PUT POST DELETE {
      # For requests that *aren't* a PUT, POST, or DELETE,
      # pass to :9080
      proxy_pass http://127.0.0.1:9080;
    }
  }
}

11
投票

我假设你已经掌握了基础知识。 I.E.,您已经在服务器上安装了Lua 5.1或更好的LuaJIT 2.0,使用ngx_lua模块编译了Nginx并根据需要配置了ngx_lua。

有了这个,这将完成工作:

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

我想也许你是在更广泛的范围内专门使用Lua。下面的例子也可以使用与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;
}

“if”和“limit_except”块都有效地创建嵌套位置块,并且一旦条件匹配,将仅执行由此创建的内部位置块的内容处理程序(“proxy_pass”)。

没有完全得到这就是为什么如果有时被称为“邪恶”,但在这种情况下,“邪恶”行为,“if”和“limit_except”共同,可能正是你想要的。

所以你可以选择三种选择!

但请注意,如果需要设置任何其他指令,则必须注意不要使用“if”或“limit_except”选项中的“邪恶”行为。

I.E.,如果你在“if”或“limit_except”块中设置一个指令,它可能在它之外不活动,同样地,外部设置的东西可以在里面继承。因此,您必须使用这两种方法来观察默认情况的继承与否,视情况而定。

If is Evil页面上列出的所有潜在问题同样适用于“if”和“limit_except”。基于Lua的脚本编写方法将避免该页面上建议的许多潜在陷阱。

祝好运!


1
投票

如果某人正在寻找通过请求方法简单地创建条件的方法,则语法为:

if ($request_method = DELETE ) {
   . . . 
}

1
投票

我推荐使用nginx map函数。这超出了您的位置块:

map $request_method $destination {
    default 8080;
    PUT 9080;
    POST 9080;
    DELETE 9080;
}

然后在您的位置栏中:

proxy_pass http://127.0.0.1:$destination

这也是所有正则表达式,所以你可以做以下事情:

map $request_method $cookie_auth $destination {
    default 8080;
    "^POST " 9080;
    "^PUT someAuthCookieValue" 9080;
}

另外,这可以避免使用if。这太棒了。我使用它将WordPress群集中的所有写入流量定向到远程节点上的一个FastCGI TCP套接字,但将读取流量发送到本地FastCGI UNIX套接字。

© www.soinside.com 2019 - 2024. All rights reserved.