nginx匹配位置中的特定单词

我在nginx $ request_bodyvariables中遇到麻烦。 我想要代理通过,如果身体请求有一个特殊的单词,

所以我的方法是这样的:

location ~ \.php$ { if ($request_body ~* (.*)) { proxy_pass http://test.proxy; break; } # other case... } 

这匹配一切和if语句的作品,但如果我以任何方式改变正则expression式,我不能得到一个命中。

所以我现在的问题是:

我如何需要正确定义正则expression式在nginx匹配,“目标”例如?

提前致谢!

你的代码有一些问题。

  1. “($ request_body〜*(。*))”与别人所说的任何东西都不匹配,所以“其他情况”总是结果

  2. 更重要的是,它使用“proxy_pass”和“if”这个古典的邪恶。 http://wiki.nginx.org/IfIsEvil

要得到你想要的,使用第三方ngx_lua模块(v0.3.1rc24及以上版本)…

 location ~ \.php$ { rewrite_by_lua ' ngx.req.read_body() local match = ngx.re.match(ngx.var.request_body, "target") if match then ngx.exec("@proxy"); else ngx.exec("@other_case"); end '; } location @proxy { # test.proxy stuff ... } location @other_case { # other_case stuff ... } 

你可以在https://github.com/chaoslawful/lua-nginx-module/tags得到ngx_lua。

PS。 请记住,lua的重写总是在nginx重写指令之后执行的,所以如果你在其他情况下使用了这些指令,它们将首先被执行,并且你将会得到一个funnies。

你应该把你所有的重写写在lua上下文中,以获得一致的结果。 这是“其他情况”的“if .. else .end”安排的原因。


您可能需要这个更长的版本


 location ~ \.php$ { rewrite_by_lua ' --request body only available for POST requests if ngx.var.request_method == "POST" -- Try to read in request body ngx.req.read_body() -- Try to load request body data to a variable local req_body = ngx.req.get_body_data() if not req_body then -- If empty, try to get buffered file name local req_body_file_name = ngx.req.get_body_file() --[[If the file had been buffered, open it, read contents to our variable and close]] if req_body_file_name then file = io.open(req_body_file_name) req_body = file:read("*a") file:close() end end -- If we got request body data, test for our text if req_body then local match = ngx.re.match(req_body, "target") if match then -- If we got a match, redirect to @proxy ngx.exec("@proxy") else -- If no match, redirect to @other_case ngx.exec("@other_case") end end else -- Pass non "POST" requests to @other_case ngx.exec("@other_case") end '; } 

手册:

注意:对于花括号({和}),因为在正则表达式和块控制中都使用它们,为了避免冲突,带有大括号的正则表达式应用双引号(或单引号)括起来。

所以试试

 if ($request_body ~* "(.*)") 

其他评论:代码.*匹配所有内容。 我会使用\w ,因为Perl的正则表达式似乎是可用的。

你目前的if语句总是错误的,所以没有命中是正确的输出。