How to Harden Nginx: Buffer Limits, Timeouts, and Security Best Practices

This guide walks through securing an Nginx web server by configuring buffer size limits, timeouts, concurrent connection controls, host and method restrictions, user‑agent blocking, hot‑link protection, directory access rules, SSL setup, PHP hardening, chroot isolation, and firewall‑level IP connection limits.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
How to Harden Nginx: Buffer Limits, Timeouts, and Security Best Practices

Control Buffer‑Overflow Attacks

Edit nginx.conf to set client buffer size limits. vi /usr/local/nginx/conf/nginx.conf Add the following directives:

## Start: Size Limits & Buffer Overflows ##
client_body_buffer_size 1k;
client_header_buffer_size 1k;
client_max_body_size 1k;
large_client_header_buffers 2 1k;
## END: Size Limits & Buffer Overflows ##

Explanation:

client_body_buffer_size – size of the buffer for request bodies; excess data is written to a temporary file.

client_header_buffer_size – size of the buffer for request headers; larger headers (e.g., big cookies) trigger allocation of a larger buffer via large_client_header_buffers.

client_max_body_size – maximum allowed request body size; exceeding it returns a 413 error.

large_client_header_buffers – number and size of buffers for large request headers; overly large headers cause a 414 error.

Timeout Settings

## Start: Timeouts ##
client_body_timeout 10;
client_header_timeout 10;
keepalive_timeout 5 5;
send_timeout 10;
## End: Timeouts ##

Explanation of each timeout directive is provided, indicating the conditions under which Nginx returns a 408 error or closes connections.

Control Concurrent Connections

Use the ngx_http_limit_conn_module to limit simultaneous connections per IP.

limit_zone slimits $binary_remote_addr 5m;
limit_conn slimits 5;

This restricts each remote IP to a maximum of five concurrent connections.

Allow Only Specified Hostnames

if ($host !~ ^(nixcraft.in|www.nixcraft.in|images.nixcraft.in)$ ) {
    return 444;
}

Restrict Allowed Request Methods

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

Only GET, HEAD, and POST are permitted; other methods such as DELETE or SEARCH are blocked.

Block Malicious User‑Agents

# Block download agents
if ($http_user_agent ~* LWP::Simple|BBBike|wget) {
    return 403;
}
# Block some robots
if ($http_user_agent ~* Sosospider|YodaoBot) {
    return 403;
}

Prevent Image Hot‑Linking

location /images/ {
    valid_referers none blocked www.example.com example.com;
    if ($invalid_referer) {
        return 403;
    }
}
# Optional redirect to a placeholder image
valid_referers blocked www.example.com example.com;
if ($invalid_referer) {
    rewrite ^/images/uploads.*\.(gif|jpg|jpeg|png)$ http://www.examples.com/banned.jpg last;
}

Directory Access Restrictions

Limit access to specific directories by IP, and protect them with passwords.

# Example: restrict /docs/ to a subnet
location /docs/ {
    deny 192.168.1.1;          # block one workstation
    allow 192.168.1.0/24;      # allow the subnet
    deny all;                  # deny the rest
}
# Create password file
mkdir /usr/local/nginx/conf/.htpasswd/
htpasswd -c /usr/local/nginx/conf/.htpasswd/passwd user
# Protect directories
location ~ /(personal-images/.*|delta/.*) {
    auth_basic "Restricted";
    auth_basic_user_file /usr/local/nginx/conf/.htpasswd/passwd;
}

SSL Configuration

Create a self‑signed certificate and configure Nginx to use it.

cd /usr/local/nginx/conf
openssl genrsa -des3 -out server.key 1024
openssl req -new -key server.key -out server.csr
cp server.key server.key.org
openssl rsa -in server.key.org -out server.key
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

server {
    server_name example.com;
    listen 443;
    ssl on;
    ssl_certificate /usr/local/nginx/conf/server.crt;
    ssl_certificate_key /usr/local/nginx/conf/server.key;
    access_log /usr/local/nginx/logs/ssl.access.log;
    error_log /usr/local/nginx/logs/ssl.error.log;
}

/usr/local/nginx/sbin/nginx -s reload

PHP Security Recommendations

# Disable dangerous functions
disable_functions = phpinfo, system, mail, exec
# Resource limits
max_execution_time = 30
max_input_time = 60
memory_limit = 8M
post_max_size = 8M
file_uploads = Off
upload_max_filesize = 2M
display_errors = Off
safe_mode = On
safe_mode_exec_dir = php-required-executables-path
expose_php = Off
log_errors = On
register_globals = Off
sql.safe_mode = On
allow_url_fopen = Off

Run Nginx in a chroot Jail

Place Nginx inside a chroot environment to limit filesystem exposure; consider using FreeBSD jails, Xen, or OpenVZ containers.

Firewall‑Level Per‑IP Connection Limits

/sbin/iptables -A INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --set
/sbin/iptables -A INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --update --seconds 60 --hitcount 15 -j DROP
service iptables save

Adjust limits according to your environment.

Protect the Web Server Filesystem

Run Nginx as the nginx user, but keep the document root owned by root and non‑writable by the Nginx user. Find files owned by the Nginx user:

find /nginx -user nginx
find /usr/local/nginx/html -user nginx

Remove backup files created by editors:

find /nginx -name '.?*' -not -name .ht* -or -name '*~' -or -name '*.bak*' -or -name '*.old*' -delete
find /usr/local/nginx/html/ -name '.?*' -not -name .ht* -or -name '*~' -or -name '*.bak*' -or -name '*.old*' -delete

Following these configurations makes the Nginx server significantly more secure.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

firewallNginxSSLbuffer
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.