背景
假设我们有一个接口 /aa 而这个接口只想让指定IP访问,且其他接口所有IP都可访问。nginx如何实现呢?
首先大家会想到用location 来实现,
location ~ .*userInfo.* {
allow xx.xx.xx.xx;
deny all;
proxy_next_upstream error timeout http_503 http_500 http_502 http_504;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
当然这样是可以达到目的,但也只限定于 url 类型 像带有参数的url地址如何匹配,如userInfo?username=789,location是不能匹配带参数的url的。举个例子
- $uri 指的是请求的文件和路径,不包含”?”或者”#”之类的东西
- $request_uri 则指的是请求的整个字符串,包含了后面请求的东西
- 例如:
- $uri: qq.com/user
- $request_uri: qq.com/user?d=1
其实写成这种最省事,也容易理解,但是ngx_http_access_module 不支持在if中使用,所以需要小小改动下代码
if ($args ~* "user?d=1"){
allow xx.xx.xx.xx;
deny all;
}
if ($request_uri~* "user?d=1"){
allow xx.xx.xx.xx;
deny all;
}
static ngx_command_t ngx_http_access_commands[] = {
{ ngx_string("allow"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LMT_CONF
|NGX_CONF_TAKE1,
ngx_http_access_rule,
NGX_HTTP_LOC_CONF_OFFSET,
0,
NULL },
{ ngx_string("deny"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LMT_CONF
|NGX_CONF_TAKE1,
ngx_http_access_rule,
NGX_HTTP_LOC_CONF_OFFSET,
0,
NULL },
ngx_null_command
};
如图就可以了,接下就可使用if来限定黑白名单了。