Nginx Configuration: Optimization & Security
Problem: stock Nginx can't handle the load
A client came with a typical Laravel 10 + PHP 8.3 project that was crashing under 1000 concurrent requests. Nginx from the repository gave frequent 502 errors, and static files loaded in 3–5 seconds. We found that worker_connections and fastcgi buffers were at defaults, caching was not configured, and rate limiting was absent. After deep optimization — aggressive caching, SSL tuning, and rate limiting — P99 latency dropped from 5 seconds to 200 ms, and the server now handles 12,000 RPS. Below are production-proven settings we apply to all projects. Contact us for a free audit.
We don't just copy generic configs; we adapt them to your specific stack. For some, micro-tuning worker_processes to CPU cores works best; for others, enabling sendfile and tcp_nopush is key. The important thing is to identify where the bottleneck is: disk, network, or backend.
Problems we solve
- Slow page loads due to inefficient static file handling and missing caching. For example, serving CSS/JS without gzip and without
expiresheaders. - Crashes under load due to misconfigured timeouts and fastcgi buffers. A common cause is
worker_connections = 1024when expecting 10k RPS. - Memory leaks from poor
worker_processesandworker_connectionssettings. On a VPS with 2 GB RAM, it's better to setautoor manually limit to 2 processes. - DDoS attacks on APIs or login pages — without rate limiting, even a simple botnet can bring the server down. We use zones keyed by
$binary_remote_addrwith limits like 30/5 requests per minute. - Insecure configuration: exposed
server_tokens, weak SSL settings, missing HSTS.
Base configuration for Laravel/PHP
We use this template for 80% of PHP projects as a starting point.
# /etc/nginx/sites-available/myapp.conf
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name example.com www.example.com;
root /var/www/myapp/current/public;
index index.php;
# SSL
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# Security headers
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
charset utf-8;
client_max_body_size 50M;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.3-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
fastcgi_read_timeout 300;
}
# Static files — maximum caching
location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff2?|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
access_log off;
}
# Deny access to hidden files
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
}
Additional settings
Reverse Proxy for Node.js
If the backend is Node.js, replace fastcgi with proxy_pass:
upstream nodejs_app {
server 127.0.0.1:3000;
server 127.0.0.1:3001;
keepalive 32;
}
server {
listen 443 ssl http2;
location / {
proxy_pass http://nodejs_app;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_read_timeout 300;
}
}
Gzip and caching
A separate file for gzip and proxy_cache:
# /etc/nginx/conf.d/gzip.conf
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 1024;
gzip_types
text/plain text/css text/xml text/javascript
application/json application/javascript application/xml+rss
application/atom+xml image/svg+xml font/ttf font/otf;
# Proxy cache (for caching backend responses)
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=app_cache:10m
max_size=1g inactive=60m use_temp_path=off;
location /api/public/ {
proxy_cache app_cache;
proxy_cache_valid 200 10m;
proxy_cache_use_stale error timeout updating;
add_header X-Cache-Status $upstream_cache_status;
proxy_pass http://app;
}
Rate Limiting
Protect APIs and login:
limit_req_zone $binary_remote_addr zone=api:10m rate=30r/m;
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
location /api/ {
limit_req zone=api burst=10 nodelay;
limit_req_status 429;
proxy_pass http://app;
}
location /login {
limit_req zone=login burst=2 nodelay;
proxy_pass http://app;
}
Logging
JSON format for integration with monitoring systems:
log_format combined_json escape=json
'{'
'"time":"$time_iso8601",'
'"remote_addr":"$remote_addr",'
'"method":"$request_method",'
'"uri":"$request_uri",'
'"status":$status,'
'"request_time":$request_time,'
'"bytes_sent":$bytes_sent,'
'"http_referer":"$http_referer",'
'"http_user_agent":"$http_user_agent"'
'}';
access_log /var/log/nginx/access.log combined_json;
error_log /var/log/nginx/error.log warn;
Configuration testing
Simple commands to verify:
| Command | Purpose |
|---|---|
nginx -t |
Validate syntax |
nginx -s reload |
Reload without downtime |
| `nginx -T | grep server_name` |
ab -n 1000 -c 100 https://example.com/ |
Load testing |
wrk -t 4 -c 100 -d 10s https://example.com/ |
Alternative to ab |
Before/After comparison
| Parameter | Default | Optimized |
|---|---|---|
| P99 latency | 5 s | 200 ms |
| Throughput | 500 RPS | 12,000 RPS |
| CPU usage | 90% | 45% |
| Static size | uncompressed | gzip level 6 |
Our process
- Audit current configuration — review log files, load, identify bottlenecks.
- Design architecture — choose the scheme (reverse proxy, standalone, with upstream).
- Implement — configure virtual hosts, SSL (Let's Encrypt or your certificate), rate limiting, caching, gzip, security headers, logging, worker optimization.
- Test — load testing (ab, wrk), security check (SSL Labs), log analysis.
- Document — configuration diagram, management commands, update instructions.
What's included
- Full configuration documentation with explanations of every parameter.
- Automation scripts for deployment (Ansible or Docker Compose).
- Monitoring and alerting setup (Prometheus + Alertmanager or equivalent).
- Training for your team: how to make changes, restart, and analyze logs.
- 30-day guarantee on configuration stability with support.
More about worker_processes selection
On a server with 4 CPU cores, it's optimal to set `worker_processes auto;` (nginx will determine the count). But if the application is memory-intensive, you can limit to 2 processes. Formula: number of CPU cores + 1 for heavy projects.Our experience
We've been working with Nginx for over 8 years. In that time, we've configured more than 100 production servers for projects ranging from landing pages to high-traffic e-commerce platforms. For each project, we deliver documentation and a 30-day guarantee on configuration stability.
According to official Nginx documentation, proper tuning at the OS level (sysctl) and worker settings can increase throughput by up to 50%.
How to configure rate limiting for DDoS protection?
Each scenario gets its own zone. For APIs, we use a limit of 30 requests per minute per IP with a burst of 10. For login, 5 requests per minute with a burst of 2. Always set limit_req_status 429 and log rejected requests. Combine with geo-filtering and fail2ban. This approach handles even basic DDoS attacks.
Why does SSL affect Core Web Vitals?
The SSL handshake directly impacts LCP and TTFB. If weak ciphers (TLS 1.0) or missing OCSP Stapling are used, handshake time can reach 300 ms. We use only TLS 1.2/1.3, modern ciphers (ECDHE+AES-GCM), and enable OCSP Stapling. This reduces TTFB by 15–20% without extra cost.
Step-by-step configuration check
- Run
nginx -tto verify syntax. - Generate load with
ab -n 1000 -c 100and monitor response statuses. - Check security headers via curl:
curl -I https://example.com | grep -i strict. - Test rate limiting: send 100 requests in 1 minute and confirm that 429 appears after exceeding the limit.
Get a free engineer consultation — we'll evaluate your project and propose an optimal Nginx configuration plan. Contact us for an audit of your current configuration.







