NGinx:如何在不使用'if'的情况下测试cookie是否设置?

Shr*_*ath 9 nginx

我目前正在使用NGinx的以下配置来测试我的应用:

location / {
            # see if the 'id' cookie is set, if yes, pass to that server.           
            if ($cookie_id){
                proxy_pass http://${cookie_id}/$request_uri;                
                break;
            }

            # if the cookie isn't set, then send him to somewhere else
            proxy_pass http://localhost:99/index.php/setUserCookie;
        }
Run Code Online (Sandbox Code Playgroud)

但他们说" IFisEvil ".任何人都可以告诉我如何在不使用"if"的情况下完成同样的工作吗?
而且,我对"if"的使用是否有问题?

kol*_*ack 10

就nginx而言,"如果是邪恶的"有两个原因.一个是,互联网上发现的许多方法将直接将htaccess重写规则转换为一系列ifs,而单独的服务器或位置将是更好的选择.其次,nginx的if语句不像大多数人期望的那样.它更像是一个嵌套的位置,有些设置不会像你期望的那样继承.这里解释它的行为.

也就是说,检查cookie之类的东西必须用ifs来完成.请务必阅读并理解ifs是如何工作的(特别是关于指令继承),你应该没问题.

您可能想要盲目地代理cookie中设置的任何主机.也许将cookie与地图结合起来以限制后端.

编辑:如果你在id cookie中使用名称而不是ip地址,你还需要一个定义的解析器,以便nginx可以查找后端的地址.此外,您的默认proxy_pass会将请求附加到setUserCookie的末尾.如果要完全代理该URL,请将该默认proxy_pass替换为:

rewrite ^ /index.php/setUserCookie break;
proxy_pass http://localhost:99;
Run Code Online (Sandbox Code Playgroud)