防止暴力破解的最基本方法是限制请求速率:
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
location /login {
limit_req zone=one burst=20 nodelay;
# 其他配置...
}
}
}
防止单个IP建立过多连接:
http {
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
limit_conn addr 10;
# 其他配置...
}
}
阻止已知的扫描工具User-Agent:
server {
if ($http_user_agent ~* (nmap|nikto|wikto|sf|sqlmap|bsqlbf|w3af|acunetix|havij|appscan)) {
return 403;
}
# 其他配置...
}
减少信息泄露:
server {
server_tokens off;
more_set_headers 'Server: Unknown';
# 其他配置...
}
server {
location ~* \.(env|log|htaccess)$ {
deny all;
}
location ~ /\. {
deny all;
}
# 其他配置...
}
server {
location /admin {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
# 其他配置...
}
}
server {
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
# 其他配置...
}
结合fail2ban可以更有效地阻止攻击者:
server {
location ~* \.(php|asp|aspx|jsp|pl|sh|py|exe)$ {
deny all;
}
# 其他配置...
}
对于更高级的保护,可以考虑安装ModSecurity:
load_module modules/ngx_http_modsecurity_module.so;
http {
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
# 其他配置...
}
这些措施可以显著提高Nginx服务器的安全性,但应根据实际业务需求进行调整和测试。