php 正则匹配指定单词,正则表达式 – nginx匹配位置中的特定单词

这篇博客讨论了Nginx配置中常见的问题,特别是关于`if`语句和`proxy_pass`的不当使用。作者建议使用ngx_lua模块来替代,并提供了详细的配置示例,确保`POST`请求的正确处理。示例代码展示了如何根据请求体内容重定向到不同的处理路径,同时避免了`if`指令的潜在问题。优化后的配置提高了代码的稳定性和效率。
摘要由CSDN通过智能技术生成

您的代码有很多问题.

>“($request_body~ *(.*))”永远不会匹配其他人所说的任何内容,因此“其他案例”始终是结果

>更重要的是,它使用“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

...

}

PS.请记住,lua的重写总是在Nginx重写指令之后执行,所以如果你在其他情况下放置任何这样的指令,它们将首先被执行,你将获得有趣的东西.

您应该将所有重写放在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

';

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值