# NGINX 配置示例:Lua 速率限制 # # 用法:将 lua_shared_dict 添加到 http 块, # 在需要限流的 location 中使用 access_by_lua_file 引入 access.lua http { # ------------------------------------------------------- # 共享内存字典:存储限流计数器 # rate_limit : 速率限制计数器 # 10m : 约可存储 160,000 个唯一键的状态 # ------------------------------------------------------- lua_shared_dict rate_limit 10m; server { listen 80; server_name api.example.com; # ------------------------------------------------------- # API 接口:启用 Lua 速率限制 # ------------------------------------------------------- location /api/ { access_by_lua_file /etc/nginx/lua/rate-limiting/access.lua; # 限流通过时添加响应头 add_header X-RateLimit-Remaining $upstream_http_x_ratelimit_remaining always; add_header X-RateLimit-Limit $upstream_http_x_ratelimit_limit always; proxy_pass http://backend_pool; } # ------------------------------------------------------- # 管理接口:不使用限流(白名单) # ------------------------------------------------------- location /admin/ { allow 10.0.0.0/24; deny all; proxy_pass http://backend_pool; } # ------------------------------------------------------- # 健康检查端点:不限流 # ------------------------------------------------------- location /health { access_log off; return 200 'ok'; } } }