Nginx提供了多种方式来限制IP访问,可以有效提升网站安全性。以下是几种常见的配置方法:
location / {
allow 192.168.1.1; # 允许单个IP
allow 192.168.1.0/24; # 允许IP段
deny all; # 拒绝其他所有IP
}
location /admin {
allow 192.168.1.100;
deny all;
}
location /secure {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
server {
location / {
limit_req zone=one burst=5;
}
}
}
http {
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
location / {
limit_conn addr 10;
}
}
}
http {
geo $blocked_country {
default 0;
include /etc/nginx/geo.conf;
}
server {
if ($blocked_country) {
return 403;
}
}
}
在/etc/nginx/geo.conf
中定义要阻止的国家IP段。
map $http_user_agent $blocked_agent {
default 0;
~*(wget|curl|nikto|sqlmap) 1;
}
server {
if ($blocked_agent) {
return 403;
}
}
location ~* \.(php|asp|aspx|jsp)$ {
if ($uri ~* "\.\.") {
return 403;
}
}
配置完成后,使用以下命令测试并重载Nginx:
nginx -t # 测试配置
nginx -s reload # 重载配置
这些配置可以根据实际需求组合使用,构建更全面的安全防护体系。