我正在编写一个Django应用程序,它使用nginx反向代理+ gunicorn作为生产中的Web服务器。
我希望包括阻止来自某个IP(或IP池)的DDOS攻击的功能。这个……
如果您想阻止某些IP甚至子网访问您的应用,请将以下代码添加到您的应用中 server 块:
server
#Specify adresses that are not allowed to access your server deny 192.168.1.1/24; deny 192.168.2.1/24; allow all;
此外,如果您不使用REST,那么您可能希望限制可能的HTTP谓词,方法是将以下内容添加到您的 server 块:
if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 403; }
为了减少DoS攻击的可能性,您可能希望限制来自单个主机的可能请求数(请参阅 http://nginx.org/en/docs/stream/ngx_stream_limit_conn_module.html ),通过在NGINX中添加以下内容 nginx.conf :
nginx.conf
limit_conn_zone $binary_remote_addr zone=limitzone:1M;
以及你的以下内容 server 块:
limit_conn limitzone 20;
其他一些有用的设置 nginx.conf ,如果设置正确,有助于缓解DoS:
server_tokens off; autoindex off; sendfile on; tcp_nopush on; tcp_nodelay on; client_body_timeout 10; client_header_timeout 10; send_timeout 10; keepalive_timeout 20 15; open_file_cache max=5000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; open_file_cache_errors on;
由于它太宽泛而无法在此解释这些,建议您查看文档 http://nginx.org/en/docs/ 详情。虽然通过特定设置的反复试验来选择正确的值。
Django将错误页面本身作为模板提供,因此您应该删除:
error_page 500 502 503 504 /500.html; location = /500.html { root /home/sarahm/djangoproject/djangoapp/templates/;
添加 access_log off; log_not_found off; 至 static 如果你真的不关心伐木也是一个选择:
access_log off; log_not_found off;
static
location /static/ { access_log off; log_not_found off; root /home/sarahm/djangoproject/djangoapp; }
这将降低文件系统请求的频率,从而提高性能。
NGINX是一个很棒的Web服务器并且设置它是一个广泛的主题,所以最好是阅读文档(至少是HOW-TO部分)或找到描述接近你的情况的设置的文章。