nginx匹配位置中的特定单词 [英] nginx match specific word in location
问题描述
我在匹配nginx $ request_body变量中的特定单词时遇到麻烦. 如果正文请求中包含特殊字词,我想代理通行证
I am having trouble matching a specific word in nginx $request_body variable. I want to proxy pass if the body request has a special word in it,
所以我的方法是这样的:
So my approach is this:
location ~ \.php$ {
if ($request_body ~* (.*)) {
proxy_pass http://test.proxy;
break;
}
# other case...
}
这将匹配所有内容,并且if语句有效, 但是如果我以任何方式更改正则表达式,都不会成功.
This matches everything and the if statement works, but if I change the regexp in any way, I can't get a hit.
所以我现在的问题是:
我该如何在nginx中正确定义正则表达式以匹配目标"?
提前谢谢!
推荐答案
您的代码有很多问题.
-
($ request_body〜*(.*))"永远不会匹配其他人说的任何内容,因此其他情况"始终是结果
"($request_body ~* (.*))" never matches anything as stated by someone else and so the the "other case" is always the outcome
更重要的是,它使用"proxy_pass"和"if",这在传统上是邪恶的. http://wiki.nginx.org/IfIsEvil .
More importantly, it uses "proxy_pass" with "if" which is classically evil. http://wiki.nginx.org/IfIsEvil.
要获得所需的内容,请使用第三方ngx_lua模块(v0.3.1rc24及更高版本)...
To get what you want, use the 3rd party ngx_lua module (v0.3.1rc24 and above) ...
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上获得ngx_lua -module/tags .
PS.请记住,总是在nginx重写指令之后执行lua重写,因此,如果在其他情况下放置任何此类指令,则将首先执行它们,并且您会得到有趣的消息.
PS. Bear in mind that rewrite by lua is always executed after the nginx rewrite directives so if you put any such directives in the other case, they will be executed first and you will get funnies.
您应该将所有重写都放在lua重写上下文中,以得到一致的结果.这就是其他情况"采用"if ..else..end"安排的原因.
You should put all your rewrites within the rewrite by lua context for consistent results. This is the reason for the "if ..else..end" arrangement for the "other case".
您可能需要更长的版本
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
';
}
这篇关于nginx匹配位置中的特定单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!