我正在编写一个Django应用程序,它使用nginx反向代理gunicorn作为生产中的Web服务器.

我希望包括阻止来自某个IP(或IP池)的DDOS攻击的功能.这是在nginx级别,而不是代码中的任何更深层次.我需要Web应用程序防火墙吗?如果是这样,我该如何整合它.

我的项目位于可用站点的nginx文件具有:

server {
    listen 80;
    charset utf-8;
    underscores_in_headers on;
    location = /favicon.ico { access_log off; log_not_found off; }

    location /static/ {

        root /home/sarahm/djangoproject/djangoapp;
    }

    location /static/admin {

        root /home/sarahm/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/contrib/admin/static/;
    }

    location / {
        proxy_pass_request_headers on;
        proxy_buffering on;
        proxy_buffers 8 24k;
        proxy_buffer_size 2k;
        include proxy_params;
        proxy_pass          http://unix:/home/sarahm/djangoproject/djangoapp/djangoapp.sock;
    }


    error_page 500 502 503 504 /500.html;
    location = /500.html {
        root /home/sarahm/djangoproject/djangoapp/templates/;
   }
}

如果我应该包含更多信息以及该信息应该是什么,请告诉我.


解决方法:

如果要阻止某些IP甚至子网访问您的应用程序,请将以下代码添加到服务器块:

#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谓词:

if ($request_method !~ ^(GET|HEAD|POST)$) {
    return 403;
}

为了减少DoS攻击的可能性,您可能希望通过向NGINX nginx.conf添加以下内容来限制来自单个主机的可能请求数(请参阅http://nginx.org/en/docs/stream/ngx\_stream\_limit\_conn\_module.html):

limit_conn_zone $binary_remote_addr zone=limitzone:1M;

以及服务器块的以下内容:

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; log\_not\_found off;如果你真的不关心日志记录也是一个选项:

location /static/ {
    access_log off;
    log_not_found off;
    root /home/sarahm/djangoproject/djangoapp;
}

这将降低文件系统请求的频率,从而提高性能.

NGINX是一个很棒的Web服务器并且设置它是一个广泛的主题,所以最好是阅读文档(至少是HOW-TO部分)或找到描述接近你的情况的设置的文章.

标签: nginx, django, security, ddos

相关文章推荐

添加新评论,含*的栏目为必填