在通常情况下,使用 nginx 基于 ip 限制访问请求频率等限制内容,我们会需要对特定ip进行限制排除操作,因此本文引入了基于nginx geo 与 nginx map 进行此类情景相关配置; 在没有人为操作删除的情况下(without-http_geo_module),nginx默认模块中已经加载了ngx-http-geo-module相关内容; ngx-http-geo-module可以用来创建变量,变量值依赖于客户端 ip 地址; ngx-http-map-module可以基于其他变量及变量值进行变量创建,其允许分类,或者映射多个变量到不同值并存储在一个变量中; ngx-http-map-module相关内容同样在默认nginx中已存在,除非由人为移除( --without-http_map_module) 二、相关指令格式 Nginx geo 格式说明 Syntax ( 语法格式 ): geo [$address] $variable { ... } Default ( 默认 ): - Content ( 配置段位 ): httpNginx map 格式说明 Syntax ( 语法格式 ): map String $variable { ... } Default ( 默认 ):- Content ( 配置段位 ): http 三、白名单配置示例 http{ # ... 其他配置内容 #定义白名单ip列表变量 geo $whiteiplist { default 1 ; #myself 127.0.0.1/32 0; #remote ip 64.223.160.0/19 0; } #使用map指令映射将白名单列表中客户端请求ip为空串 map $whiteiplist $limit{ 1 $binary_remote_addr ; 0 ""; } #配置请求限制内容 limit_req_zone $limit zone=foo:1m rate=10r/m; } server{ location /yourApplicationName { proxy_pass http://192.168.1.111:8095/app; # 在 server 中进行限制配置引用 zone = foo limit_req zone=foo burst=5 nodelay; } }白名单配置可用于对合作客户,搜索引擎等请求过滤限制 #(特殊情况处理) #如果想仅限制指定的请求,如:只限制Post请求,则: http{ # 其他请求.. #请求地址map映射 map $request_method $limit { default ""; POST $binary_remote_addr; } #限制定义 limit_req_zone $limit zone=reqlimit:20m rate=10r/s; } #然后在server中进行引用。 server{ ... #与普通限制一致 } #在此基础上,想进行指定方法的白名单限制处理,则: http{ #... #定义白名单列表 map $whiteiplist $limitips{ 1 $binary_remote_addr; 0 ""; } #基于白名单列表,定义指定方法请求限制 map $request_method $limit { default ""; # POST $binary_remote_addr; POST $limitips; } #对请求进行引用 limit_req_zone $limit zone=reqlimit:20m rate=10r/s; #在server中进行引用 server{ #... 与普通限制相同 } # 对应用中指定请求路径不设置限制,如对请求路径为 即api目录下的请求不做 # 限制,则可写为 server{ location /app { proxy_pass http://192.168.1.111:8095/app; limit_req zone=foo burst=5 nodelay; } location /app/api { proxy_pass http://192.168.1.111:8095/app/api } } # 因nginx会优先进行精准匹配,所以以上写法即接触了对api目录下属路径的限制 转载请保留固定链接: https://linuxeye.com/configuration/2823.html |