by 🇷🇺 Dmitry Lezhnev
Web Backend Developer
PHP/LEMP-stack practitioner
Zend Certified Engineer
Clean Architecture advocate


PHP version 7+ Nginx web-server MySQL Linux Ubuntu Jet Brains Docker
Remote developer





Mon, 2 May 2016

# Protect your site from ddos with free built-in nginx feature ngx_http_limit_req_module

Table of Contents

    When you expect (or not) your website to be a target of malicious traffic – make some free efforts to protect from it. Use nginx option to limit connections allowed per IP. This is not the only thing you could do but this is the least thing you should do.

    Option `ngx_http_limit_req_module` lets you to set limitations of simultaneous connection per IP. 

    http {
        # define a rule (zone) which should be applied to every IP ($binary_remote_addr)
        limit_req_zone $binary_remote_addr zone=ZONE_NAME:10m rate=2r/s;
    
        ...
    
        server {
    
            ...
    
            location /search/ {
                # apply rule (zone) to this location
                # also set a safe buffer (burst) for spikes in connections which will queue requests until full
                limit_req zone=ZONE_NAME burst=5;
                ...
            }
            ...
        }
    }
    
    Limit connections to search page

    Also use logging to have a picture of how often this rule is triggered. If your users feel that they see 503 error too often – increase the value and make informative decision about it.

    Also make a nice image for the 503 situation. And set nginx to show it so your users will get better UX even when faced with 503 page.

    server {
    ...
        
        error_page 503 @503;
        location @503 {
           rewrite ^(.*)$ /503.html break;
        }
    
    }
    
    set 503 custom page

    So User will see nice page instead of standard nginx page:

    503 standard page
    503 standard page

     







    ATOM feed | Website source code