我有一个服务通过nginx访问,我只希望白名单发布请求。 我已经写在我的nginxconfiguration文件中:
location / { if ( $request_method ~ ^(POST|PUT)$ ) { allow 127.0.0.1; } if ( $request_method !~ ^(GET|POST|PUT|HEAD)$ ) { return 405; } }
这个configuration给我下面的错误 –
nginx: [emerg] "allow" directive is not allowed here
另一方面,如果我写这样的if块的allow指令,它的工作原理。
location / { allow 127.0.0.1; if ( $request_method !~ ^(GET|POST|PUT|HEAD)$ ) { return 405; } }
我相信这意味着我不能在if块中使用allow指令。 我在这里做错了什么? 如果没有,是否有解决方法来实现这一目标?
http { geo $allowed_post_put { default 0; 127.0.0.1 1; ::1 1; } map $request_method:$allowed_post_put $return_405 { "POST:0" 1; "PUT:0" 1; } } location / { if ( $return_405 = 1 ) { return 405; } }
http://nginx.org/en/docs/http/ngx_http_geo_module.html – 地理模块允许根据客户端IP地址创buildvariables。
http://nginx.org/en/docs/http/ngx_http_map_module.html – 地图模块创build值取决于其他variables值的variables。
if来自重写模块的指令不允许复杂的逻辑expression式,只需要单个variables比较。 所以我们使用map模块来创build依赖于客户端IP和请求方法的variables。
UPD :与地理/地图相似的configuration/如果黑客在我的生产环境中工作的很好。