3

当且仅当 cookie 存在时,我想将 URL 重定向到 Django 平台(通过 uwsgi)。如果做不到这一点,我需要将执行推迟到content_by_lua插件。

以下是我对这种逻辑的尝试:

location ~* "^/[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$" {  # match a UUID v4
    include uwsgi_params;
    if ($cookie_admin) {
        # if cookie exists, rewrite /<uuid> to /modif/<uuid> and pass to uwsgi
        rewrite ^/([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})$ /modif/$1 break; 
        uwsgi_pass frontend;
    }
    content_by_lua '
        ngx.say("Ping!  You got here because you have no cookies!")
    ';
}

Nginx 认为用以下日志消息侮辱我的智力是必要和适当的:

nginx: [emerg] directive "rewrite" is not terminated by ";" in /opt/openresty/nginx/conf/nginx.conf:34

也许我和 nginx 想的一样密集,但我错过了什么?

额外的问题:我的一般方法安全和理智吗?有没有更好的方法来实现我的目标?

4

2 回答 2

12

对我来说,这实际上是一件非常愚蠢的事情。Nginx 使用花括号{}来分隔块,因此当它们在正则表达式中使用时,表达式必须用双引号括起来。

于 2016-01-17T23:33:09.387 回答
1

奖励答案:您也可以在位置匹配期间捕获 UUID 值,以避免重写时出现额外的正则表达式,如下所示:

location ~* "^/([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})$" {  # match and capture a UUID v4
  include uwsgi_params;
  set $uuid $1;
  if ($cookie_admin) {
    # if cookie exists, rewrite /<uuid> to /modif/<uuid> and pass to uwsgi
    rewrite / /modif/$uuid break; 
    uwsgi_pass frontend;
  }
  content_by_lua '
    ngx.say("Ping!  You got here because you have no cookies!")
    ngx.say("UIID: " .. ngx.var.uuid)
 ';
}
于 2016-01-18T00:10:40.497 回答