为什么nginx声称我的`rewrite`语句中没有终止分号?

如果且仅当存在 cookie 时,我想要将 URL 重定向到 Django 平台(通过 uwsgi)。如果失败,我需要将执行延迟到 content_by_lua 插件。

以下是我尝试实现此逻辑的代码:

location ~* "^/[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$" {  # 匹配 UUID v4
    include uwsgi_params;
    if ($cookie_admin) {
        # 如果 cookie 存在,将 /<uuid> 重写为 /modif/<uuid> 并传递给 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 认为的那样愚蠢,但我错过了什么?

奖励问题:我这样做的总体方法是否安全可靠?是否有更好的实现方法?

点赞
用户1156707
用户1156707

这实际上是我弄错的一个非常愚蠢的事情。Nginx使用花括号 {} 来分隔块,因此当这些被用于正则表达式时,表达式必须用双引号括起来。

2016-01-17 23:33:09
用户1058509
用户1058509

加分答案: 你也可以在位置匹配期间捕获 UUID 值,以避免在重写时进行额外的正则表达式匹配,像这样:

location ~* "^/([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})$" {  # 匹配并捕获 UUID v4
  include uwsgi_params;
  set $uuid $1;
  if ($cookie_admin) {
    # 如果 cookie 存在,将 /<uuid> 重写为 /modif/<uuid> 并传递给 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-18 00:10:40