Nginx提供了多种方式控制HTTP访问:
location /admin/ {
# 允许特定IP
allow 192.168.1.1;
allow 192.168.1.2;
# 拒绝所有其他IP
deny all;
# 其他配置...
}
location /secure/ {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location /downloads/ {
valid_referers none blocked server_names *.example.com;
if ($invalid_referer) {
return 403;
}
}
# 在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_server;
}
}
# 在http块中定义连接限制区域
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
location /download/ {
limit_conn conn_limit 5;
proxy_pass http://backend_server;
}
}
location /upload/ {
client_max_body_size 10m;
proxy_pass http://backend_server;
}
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;
server {
location / {
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_pass http://backend_server;
}
}
upstream backend {
server backend1.example.com;
server backend2.example.com;
# 健康检查配置
check interval=3000 rise=2 fall=3 timeout=1000;
}
location / {
proxy_pass http://backend;
}
# 需要安装ngx_http_geoip_module
geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
default no;
US yes;
CA yes;
GB yes;
}
server {
if ($allowed_country = no) {
return 403;
}
# 其他配置...
}
# 在http块中
map $time_iso8601 $outside_office_hours {
default 0;
"~T0[89]:" 0; # 08:00-09:59
"~T1[0-7]:" 0; # 10:00-17:59
"~*" 1;
}
server {
location /restricted/ {
if ($outside_office_hours) {
return 403;
}
# 其他配置...
}
}
通过合理配置这些访问控制和请求限制功能,可以显著提高Nginx服务器的安全性和稳定性。