location / {
# 允许特定IP或IP段
allow 192.168.1.0/24;
allow 10.0.0.1;
# 拒绝其他所有
deny all;
proxy_pass http://backend;
}
location /admin {
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://backend;
}
location /api {
limit_except GET POST {
deny all;
}
proxy_pass http://backend;
}
location /downloads {
valid_referers none blocked example.com *.example.com;
if ($invalid_referer) {
return 403;
}
proxy_pass http://backend;
}
http {
limit_conn_zone $binary_remote_addr zone=perip:10m;
limit_conn_zone $server_name zone=perserver:10m;
server {
limit_conn perip 10; # 每个IP最多10个连接
limit_conn perserver 100; # 整个服务器最多100个连接
}
}
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
location /api {
limit_req zone=one burst=20 nodelay;
proxy_pass http://backend;
}
}
}
location /download {
proxy_pass http://backend;
proxy_buffering on;
proxy_buffers 16 8k;
proxy_buffer_size 8k;
limit_rate 500k; # 限制下载速度为500KB/s
}
http {
geo $limited_country {
default 0;
CN 1;
US 1;
# 其他允许的国家
}
map $limited_country $limit_key {
0 "";
1 $binary_remote_addr;
}
limit_req_zone $limit_key zone=country:10m rate=5r/s;
server {
location / {
limit_req zone=country burst=10;
proxy_pass http://backend;
}
}
}
location /api {
# 根据URI不同部分设置不同限流策略
if ($request_uri ~* "^/api/v1/search") {
set $limit_rate 100k;
}
if ($request_uri ~* "^/api/v1/download") {
set $limit_rate 500k;
}
proxy_pass http://backend;
}
http {
upstream backend {
server backend1.example.com max_fails=3 fail_timeout=30s;
server backend2.example.com;
}
server {
location / {
# 当后端错误率超过20%时返回503
proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
proxy_next_upstream_tries 3;
proxy_next_upstream_timeout 10s;
proxy_pass http://backend;
}
}
}
map $time_iso8601 $is_business_hours {
default 0;
"~T0[89]:|~T1[0-7]:" 1; # 08:00-17:59
}
server {
location / {
if ($is_business_hours = 0) {
return 503;
}
proxy_pass http://backend;
}
}
通过合理配置Nginx的这些功能,可以有效地保护后端服务不被过载,同时确保关键业务流量的优先级。