GadElKareem

Limiting connections and requests to WordPress with Nginx

WordPress could get very slow if used without limitations or protection. I wrote about Nginx HttpLimitReqModule and HttpLimitZoneModule a while ago which could be customised as following to protect WordPress blog.

http{
    ....

    geo $limited {
        default 1;
        127.0.0.1 0;
    }

    map $limited $limit {
        1        $binary_remote_addr;
        0        "";
    }

    #http://wiki.nginx.org/HttpLimitConnModule
    #concurrent connections limited to 200
    limit_conn_zone  $limit  zone=concurrent:10m;
    limit_conn_log_level warn;
    limit_conn  concurrent  200;


    #http://wiki.nginx.org/HttpLimitReqModule
    #PHP serve zone to limit requests to 50 per second
    limit_req_zone $limit zone=php:10m rate=50r/s;

    #limit searches to 100 request per minute
    limit_req_zone $limit zone=search:10m rate=100r/m;

    #login zone to limit login request to 1 request per second
    limit_req_zone $limit zone=login:10m rate=1r/s;

    limit_req_log_level  warn;

    server {
        .....

        error_page 449 = @search;
        #limit search requests
        if ( $arg_s ){
            return 449;
        }
        location @search {
            limit_req   zone=search nodelay;
            rewrite / /index.php?$args last;
            include /etc/nginx/fastcgi_params;
        }

        location = /wp-login.php {
            limit_req  zone=login nodelay;
            include /etc/nginx/fastcgi_params;
        }

        location ~ \.php$ {
            limit_req zone=php burst=50;
            include /etc/nginx/fastcgi_params;
        }