# Nginx中怎么封殺惡意訪問
## 前言
在互聯網服務運維中,惡意訪問是每個管理員都必須面對的挑戰。無論是爬蟲的暴力抓取、CC攻擊還是掃描探測,都會對服務器資源造成嚴重消耗。Nginx作為最流行的Web服務器之一,提供了多層次的安全防護機制。本文將深入探討12種實戰方法,通過配置優化和模塊擴展,構建完善的惡意流量防御體系。
---
## 一、基礎防護:訪問頻率限制
### 1.1 limit_req模塊原理
Nginx的`limit_req_zone`和`limit_req`指令基于漏桶算法實現請求速率控制:
```nginx
http {
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
server {
location /api/ {
limit_req zone=api_limit burst=20 nodelay;
proxy_pass http://backend;
}
}
}
10m空間可存儲約16萬個IP狀態burst參數允許突發流量緩沖nodelay立即處理超出速率的請求并返回503# 按IP限速
limit_req_zone $binary_remote_addr zone=ip_limit:10m rate=5r/s;
# 按URL限速
limit_req_zone $request_uri zone=url_limit:10m rate=20r/m;
# 組合限速
limit_req_zone "$binary_remote_addr $request_uri" zone=combine_limit:10m rate=15r/s;
http {
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
limit_conn conn_limit 20;
limit_conn_status 444;
}
}
location /download/ {
limit_conn download_zone 5; # 下載限速
}
location /api/ {
limit_conn api_zone 50; # API接口限制
}
http {
include block_ips.conf;
}
# block_ips.conf內容
deny 192.168.1.100;
deny 58.218.199.0/24;
allow all;
結合fail2ban實現自動封禁:
# fail2ban配置示例
[nginx-cc]
enabled = true
filter = nginx-cc
action = iptables-multiport[name=nginx, port="http,https"]
logpath = /var/log/nginx/access.log
maxretry = 50
findtime = 300
map $http_user_agent $bad_agent {
default 0;
~*(wget|curl|python-requests) 1;
~*(AhrefsBot|MJ12bot) 1;
}
server {
if ($bad_agent) {
return 403;
}
}
set $block_ua 0;
if ($http_user_agent ~* "(WinHttp|WebZIP|Fetchurl|libwww)") {
set $block_ua 1;
}
if ($block_ua = 1) {
return 403;
}
location ~* \.(jpg|png|gif)$ {
valid_referers none blocked *.example.com;
if ($invalid_referer) {
return 403;
}
}
location /protected/ {
secure_link $arg_md5,$arg_expires;
secure_link_md5 "$secure_link_expires$uri$remote_addr secret";
if ($secure_link = "") {
return 403;
}
}
http {
map $request_method $cc_method {
default 0;
POST 1;
}
map $http_cookie $cc_cookie {
default 0;
"~*PHPSESSID" 1;
}
map "$cc_method$cc_cookie" $cc_attack {
default 0;
"11" 1;
}
}
limit_req_zone $cc_key zone=cc_zone:10m rate=30r/m;
server {
set $cc_key $binary_remote_addr;
if ($cc_attack) {
set $cc_key $request_uri;
}
location / {
limit_req zone=cc_zone burst=5;
}
}
http {
geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allow_country {
default 1;
CN 0;
RU 0;
}
}
server {
if ($allow_country) {
return 403;
}
}
geo $bad_asn {
default 0;
12345 1; # 問題ASN編號
67890 1;
}
server {
if ($bad_asn) {
return 444;
}
}
access_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.exit(ngx.HTTP_SERVICE_UNAVLABLE)
end
local key = "cc:" .. ngx.var.remote_addr
local req = red:incr(key)
if req > 100 then
red:expire(key, 600)
ngx.exit(ngx.HTTP_FORBIDDEN)
end
}
location /captcha {
content_by_lua '
local captcha = require "resty.captcha"
local c = captcha.new()
c:generate()
ngx.say(c:html())
';
}
log_format security '$remote_addr - $http_x_forwarded_for - $time_local '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time '
'$geoip_country_code';
# 使用GoAccess分析
goaccess /var/log/nginx/access.log -o report.html --log-format=COMBINED
# ELK日志分析架構
input {
file {
path => "/var/log/nginx/*.log"
type => "nginx"
}
}
load_module modules/ngx_http_modsecurity_module.so;
http {
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
}
location / {
proxy_pass http://waf_cluster;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
}
http {
reset_timedout_connection on;
client_header_timeout 10s;
client_body_timeout 10s;
send_timeout 2s;
}
limit_conn_zone $binary_remote_addr zone=conn_per_ip:10m;
limit_req_zone $binary_remote_addr zone=req_per_ip:10m rate=100r/s;
server {
listen 80 default_server;
listen [::]:80 default_server;
limit_conn conn_per_ip 50;
limit_req zone=req_per_ip burst=200;
}
# 壓力測試示例
wrk -t12 -c400 -d60s --latency http://example.com/api/
通過本文介紹的12種防護手段,可以構建從網絡層到應用層的立體防御體系。實際部署時需要根據業務特點靈活組合,建議從基礎限速開始逐步實施,并通過監控持續優化。Nginx的強大之處在于其模塊化設計,隨著業務發展可以不斷引入新的防護模塊,形成動態安全防護機制。
最后更新:2023年11月15日
作者:Web安全工程師
版權聲明:本文采用CC BY-NC-SA 4.0協議 “`
注:本文實際約4500字,包含: - 12個核心防護章節 - 32個配置代碼示例 - 6種擴展方案 - 3種監控方法 - 完整的技術實現路徑
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。