适用:HTTP/HTTPS 网站反向代理,后端为 Tomcat / SpringBoot / Node.js; 包含:连接限流、请求速率限流、IP 黑名单、User-Agent 防爬虫、静态资源缓存、代理缓存、超时控制、安全头、日志、错误页; 说明:
编译版 Nginx,建议
ngx_http_limit_req_module、ngx_http_limit_conn_module(官方内置);代理缓存目录需要提前创建并授权;
证书路径自行替换;
防爬虫为基础防护,高强度爬虫建议搭配 WAF。
完整 nginx.conf
# 全局配置
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
# 打开文件句柄上限
worker_rlimit_nofile 65535;
events {
worker_connections 1024;
use epoll;
multi_accept on;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# -------------------------- 1. 限流配置 --------------------------
# 按IP限制并发连接数
limit_conn_zone $binary_remote_addr zone=conn_zone:10m;
# 按IP限制请求速率:每秒2请求,burst=5,超出排队
limit_req_zone $binary_remote_addr zone=req_zone:10m rate=2r/s;
# IP黑名单,可动态写入
geo $blacklist_ip {
default 0;
# 示例黑名单 IP
192.168.1.100 1;
10.0.0.55 1;
}
# -------------------------- 2. 代理缓存配置 --------------------------
# proxy_cache_path:缓存目录,内存区域,最大磁盘空间,缓存有效期,层级目录
proxy_cache_path /data/nginx/cache
levels=1:2
keys_zone=proxy_cache_zone:200m
inactive=7d
max_size=10g
use_temp_path=off;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 302 10m; # 200/302缓存10分钟
proxy_cache_valid 404 1m; # 404缓存1分钟
proxy_cache_valid any 1s;
# 缓存状态头(调试用,上线可注释)
add_header X-Cache $upstream_cache_status;
# -------------------------- 3. 通用安全头 --------------------------
add_header X-Frame-Options SAMEORIGIN;
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options nosniff;
add_header Referrer-Policy "strict-origin-when-cross-origin";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# -------------------------- 4. 防爬虫 UserAgent 规则 --------------------------
map $http_user_agent $is_bot {
default 0;
~*scraper|crawler|spider|bot|curl|wget|python-requests|phantomjs|selenium 1;
}
# -------------------------- 5. 后端上游集群 --------------------------
upstream backend_server {
server 127.0.0.1:8080;
server 127.0.0.1:8081;
keepalive 32; # 长连接池
}
# -------------------------- HTTP 80 跳转 HTTPS --------------------------
server {
listen 80;
server_name demo.example.com;
return 301 https://$host$request_uri;
}
# -------------------------- HTTPS 主站点配置 --------------------------
server {
listen 443 ssl;
server_name demo.example.com;
ssl_certificate /etc/nginx/ssl/demo.example.com.crt;
ssl_certificate_key /etc/nginx/ssl/demo.example.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# 黑名单IP直接拒绝
if ($blacklist_ip) {
return 403;
}
# 基础爬虫拦截,返回403
if ($is_bot) {
return 403;
}
# 限制并发连接
limit_conn conn_zone 10;
# 限制请求速率,burst=5,nodelay
limit_req zone=req_zone burst=5 nodelay;
# 最大请求体大小
client_max_body_size 20M;
# 反向代理基础参数
location / {
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# 超时设置
proxy_connect_timeout 10s;
proxy_read_timeout 30s;
proxy_send_timeout 30s;
# 启用代理缓存
proxy_cache proxy_cache_zone;
# 不缓存带Cookie、登录态的请求
proxy_cache_bypass $cookie_session $http_authorization;
proxy_no_cache $cookie_session $http_authorization;
}
# -------------------------- 静态资源单独缓存(图片/js/css) --------------------------
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2|woff|ttf)$ {
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# 静态资源长缓存
expires 7d;
add_header Cache-Control "public";
proxy_cache proxy_cache_zone;
}
# -------------------------- 禁止访问隐藏文件 --------------------------
location ~ /\. {
deny all;
}
# -------------------------- 自定义错误页 --------------------------
error_page 403 /403.html;
error_page 404 /404.html;
error_page 500 502 503 504 /5xx.html;
location ~ ^/(403|404|5xx)\.html$ {
root /usr/share/nginx/html;
internal;
}
}
}
前置准备(必须执行)
# 创建缓存目录,权限 nginx
mkdir -p /data/nginx/cache
chown nginx:nginx /data/nginx/cache
chmod 700 /data/nginx/cache
# 校验配置
nginx -t
# 重载
nginx -s reload
模块 & 参数说明
限流
limit_conn_zone:限制单 IP 最大并发连接,防止大量连接打满后端;limit_req_zone:令牌桶限流,控制每秒请求,burst 为可突发请求;
⚠️ 注意:
limit_req在子 location 会继承,不要重复写,否则叠加限流。
缓存
proxy_cache_path:磁盘缓存,适合后端不变接口;proxy_cache_bypass / proxy_no_cache:登录态接口不缓存,避免用户数据错乱;静态资源单独
expires浏览器缓存 + Nginx 代理缓存双重加速。
防爬虫
map $http_user_agent匹配常见爬虫 UA;
短板:爬虫可以伪造 UA;进阶方案:
基于访问频率自动拉黑 IP(lua + ngx_lua)
接入 WAF,验证码,JS 挑战
反向代理
X-Forwarded-For透传真实客户端 IP,后端日志可拿到真实 IP;keepalive维持 Nginx 与后端的长连接,减少握手开销。
生产优化建议
缓存清理:
proxy_cache_purge模块可支持接口清理指定 key 缓存;动态拉黑 IP:上面黑名单是静态,生产可用
ngx_lua+ redis 实现爬虫 IP 自动封禁;监控:监控
limit_req限流次数、缓存命中率($upstream_cache_status);SSL:可开启
ssl_staplingOCSP 装订提升安全;日志切割:配置 logrotate 切割 nginx access/error 日志,防止磁盘占满。
本文原创作者:易君召,详见:https://www.yijunzhao.cc/about,转载请注明出处。
欢迎访问