Nginx实战-公网LB限流配置等

发布时间 2023-11-21 10:23:24作者: 付同學

前提: Nginx要实现根据ip地址进行限流与不限流的区分需要通过源码包安装GeoIP模块

找到与yum安装版本相同的源码包,通过configure进行安装

./configure  --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp  --with-file-aio --with-ipv6 --with-http_auth_request_module --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_addition_module   --with-http_geoip_module=dynamic --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_degradation_module --with-http_slice_module --with-http_stub_status_module --with-http_perl_module=dynamic --with-mail=dynamic --with-mail_ssl_module --with-pcre --with-pcre-jit --with-stream=dynamic --with-stream_ssl_module  --with-debug

通过GeoIP模块对访问IP进行分流

geo $unlimit {
        default 1;
        172.29.72.110/32 0;
}

map $unlimit $limit_key {
        0 "";
        1 "11000000101010000000000100000001";
}

limit_req_zone $limit_key zone=public_zone:1m rate=50r/s;
主要思路为将不同ip对应上不同的ulimit值,再通过map函数来给limit_key赋值,限流范围的IP都映射为一个二进制字符串确保使用同一块共享内存空间,再通过public_zone对这块共享内存区域进行限速定义
limit_req zone=public_zone burst=100 nodelay;
limit_req_status 429;
这里是http模块里对于限流的使用与状态码的修改

通过Proxy_cache模块对静态文件进行缓存

proxy_cache_path /etc/nginx/cache levels=1:2 keys_zone=hot_cache:512m inactive=3d max_size=5g;
proxy_cache_path:这是用于配置Nginx缓存路径的指令。它指定了缓存文件的存储路径,这里指定为/etc/nginx/cache。levels=1:2表示缓存路径的目录结构,keys_zone=hot_cache:512m指定了一个名为hot_cache的缓存区域,大小为512MB。这个区域会存储缓存的键值对信息。inactive=3d表示缓存文件在3天没有被访问后会被认为是不活跃的,可以被清理。max_size=5g指定了缓存的最大大小为5GB。
Cache定义后的使用,对静态文件的缓存
location *.(js|css|ico) {
                proxy_cache hot_cache;
                proxy_cache_valid 200 206 304 301 302 1d;
                proxy_cache_valid any 30m;
                proxy_cache_key $host$uri$is_args$args;
                proxy_cache_min_uses 3;
                proxy_cache_lock on;
                proxy_cache_lock_timeout 3s;
                add_header Cache-status $upstream_cache_status;
}

image

定义非直接访问配置
referer头的判断和service的判断
set $flag 0;
if ($http_referer ~* ".*\.tp-link\.com") {
                set $flag 1;
}
if ($arg_service ~* "^https?%3A%2F%2F") {
                set $flag 1;
}
if ($flag != 1) {
                return 400;
}