nginx+lua+redis对访问url以及ip进行分流

  • nginx+lua+redis对访问url以及ip进行分流已关闭评论
  • 55 views
  • A+
所属分类:nginx

安装

# 1.下载源码包 
wget https://openresty.org/download/openresty-1.11.2.2.tar.gz 
tar -xzvf openresty-1.11.2.2.tar.gz 
cd openresty-1.11.2.2 
#2.编译安装  
--prefix=/opt/openresty/nginx --with-cc-opt=-O2 --add-module=../ngx_devel_kit-0.3.0 --add-module=../iconv-nginx-module-0.14 --add-module=../echo-nginx-module-0.61 --add-module=../xss-nginx-module-0.05 --add-module=../ngx_coolkit-0.2rc3 --add-module=../set-misc-nginx-module-0.31 --add-module=../form-input-nginx-module-0.12 --add-module=../encrypted-session-nginx-module-0.06 --add-module=../ngx_postgres-1.0 --add-module=../srcache-nginx-module-0.31 --add-module=../ngx_lua-0.10.10 --add-module=../ngx_lua_upstream-0.07 --add-module=../headers-more-nginx-module-0.32 --add-module=../array-var-nginx-module-0.05 --add-module=../memc-nginx-module-0.18 --add-module=../redis-nginx-module-0.3.7 --add-module=../rds-json-nginx-module-0.14 --add-module=../rds-csv-nginx-module-0.07 --with-ld-opt=-Wl,-rpath,/opt/openresty/luajit/lib --with-http_ssl_module
gmake 
gmake install

下载安装redis

 

wget http://download.redis.io/releases/redis-2.8.3.tar.gz  
tar xzf redis-2.8.3.tar.gz  
cd redis-2.8.3  
make
pwd
/opt/redis-2.8.3/src
./redis-server ../redis.conf

配置nginx

#user nobody;
worker_processes 1;
events {
 worker_connections 1024;
}
http {
 include mime.types;
 default_type application/octet-stream;
 sendfile on;
 keepalive_timeout 65;
server {
 listen 80;
 server_name 127.0.0.1;
location / {
 root html;
 index index.html index.htm;
access_by_lua_file /opt/openresty/lua/my_access_limit.lua;
proxy_pass http://127.0.0.1:8080;
 client_max_body_size 1m;
 }
}
}

其中,/opt/openresty/lua/my_access_limit.lua文件内容如下:

ngx.req.read_body()

local redis = require "resty.redis"
local red = redis.new()
red.connect(red, '127.0.0.1', '6379')

local myIP = ngx.req.get_headers()["X-Real-IP"]
if myIP == nil then
 myIP = ngx.req.get_headers()["x_forwarded_for"]
end
if myIP == nil then
 myIP = ngx.var.remote_addr
end
 
if ngx.re.match(ngx.var.uri,"^(/weather/).*$") then
 local method = ngx.var.request_method
 if method == 'POST' then
 local args = ngx.req.get_post_args()
 
 local hasIP = red:sismember('black.ip',myIP)
 local hasIMSI = red:sismember('black.imsi',args.imsi)
 local hasTEL = red:sismember('black.tel',args.tel)
 if hasIP==1 or hasIMSI==1 or hasTEL==1 then
 --ngx.say("This is 'Black List' request")
 ngx.exit(ngx.HTTP_FORBIDDEN)
 end
 else
 --ngx.say("This is 'GET' request")
 ngx.exit(ngx.HTTP_FORBIDDEN)
 end
end

给redis添加数据

这里就塞一条数据,其他的就暂时不塞了

sadd black.imsi '460123456789'

启动nginx

/opt/openresty/nginx/sbin/nginx

验证结果

curl -d "imsi=460123456789" "http://www.mysite.com/weather/api"
返回403

 

  • 我的微信
  • 微信扫一扫
  • weinxin
  • 微信公众号
  • 微信公众号扫一扫
  • weinxin
avatar