- Published on
Hardening high-traffic WordPress at Nginx: rate limits, microcaching

- Authors

- Name
- Nadim Tuhin
- @nadimtuhin
On this page
High-traffic WordPress sites rarely die from sophisticated zero-days.
They die from the boring stuff: automated scrapers hammering XML-RPC, login brute-force exhausting php-fpm worker pools, and cache misses pushing MySQL to 100% CPU.
The fix is to drop bad requests at Nginx, before they ever touch PHP or the database. Here's the layered setup, one layer at a time.
The challenge
Consider a WordPress multisite serving content in multiple languages:
- Main site (English):
/ - Secondary language:
/lang1 - Tertiary language:
/lang2
Each site needs its own security considerations, but the protection has to stay consistent across the platform. High-traffic sites typically face these challenges:
- Target profile: Automated scanners, bad bots, SQL injection probes, and brute-force login attempts hit the origin nonstop.
- Resource drain: Heavy scanning causes high CPU usage, increased bandwidth consumption, slower response times for legitimate users, and occasional timeouts during peak scan periods.
- Multilingual pathing: Managing security across multiple sites means more entry points to protect, complex URL patterns to secure, and maintaining consistent rules across all language variants.
- WordPress entry points: Plugin vulnerabilities, theme issues, core exploits, and file upload vulnerabilities.
Request flow through security layers
Every incoming request passes through these layers in order. Think of each one as a bouncer who only lets the next one see what got past:
| Layer | Check | Action on fail |
|---|---|---|
| Edge filtering | Transport headers, bad URIs, SQLi, XSS | 403/444 Blocked, headers set |
| XML-RPC and brute-force mitigation | wp-config.php, xmlrpc.php, uploads, rate limits | 403 Denied, request throttled |
| Microcaching under attack | Static assets, cached dynamic responses | Serve directly from cache |
| Upstream buffer tuning | Backend proxy buffers, worker timeouts | Absorb bursts, protect PHP pool |
If not static or cached: Request proceeds to Apache/PHP Handler (WordPress Core).

Edge filtering
Start at the edge, with security headers and perimeter checks that guard against common web vulnerabilities.
Transport security headers
# Prevent version disclosure
server_tokens off;
# HSTS for enforcing HTTPS
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
# Prevent clickjacking attacks
add_header X-Frame-Options SAMEORIGIN always;
# Disable content-type sniffing
add_header X-Content-Type-Options nosniff always;
# Content Security Policy - the modern replacement for X-XSS-Protection
# Customize based on your site's requirements
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; frame-ancestors 'self';" always;
# Note: X-XSS-Protection is deprecated - Chrome removed XSS Auditor in 2019
# Modern browsers ignore this header. Use Content-Security-Policy instead.
Together, the headers above are your first line of defense against common attack vectors.
Important: Always add
alwaystoadd_headerdirectives to ensure headers are sent even on error responses.
Perimeter rules and path sanitization
Drop hidden files, disable directory listing, and short-circuit common scanner targets:
# Prevent directory listing
autoindex off;
# Block hidden files (like .git, .htaccess)
location ~ /\. { deny all; }
# Handle favicon and robots.txt efficiently
location = /favicon.ico {
log_not_found off;
access_log off;
}
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
try_files $uri /index.php?$args;
}
Attack pattern filtering
Block known exploit payloads at the edge, before queries hit the database or the PHP runtime.
Why these rules use
$request_uriand notlocation: nginx matcheslocationblocks against the normalized path only. It decodes%XXsequences, resolves.and..segments and merges repeated slashes first, and the query string isn't part of the match. Alocationrule never sees a payload in?id=..., and it can't see../or//after normalization. So the rules below test$request_uriinstead, which holds the original path plus the query string exactly as the client sent them. See the nginxlocationdocs and$request_uri.The catch:
$request_uri(like$args) is not URL-decoded. Each pattern lists the raw character and its single-encoded form (%27for',%3Cfor<,%2e%2efor..) and treats%20and+as spaces. Double encoding (%2527) and other tricks still slip past, which is one more reason these rules are a filter for noisy scanners, not your real defense.
All the rules in this section go in the server block. An if that only does return is the safe way to use if in nginx, and it runs before any location is picked, so a blocked request never reaches PHP.
SQL injection protection
Caveat: Regex-based SQL injection detection at the nginx level is a defense-in-depth measure, not a primary protection. It can produce false positives (for example, a search for a quoted title that starts with "And" or "Select") and is easily bypassed with encoding tricks. Always use parameterized queries/prepared statements as your primary defense.
# Block obvious SQL injection attempts in the path or query string
# Note: This catches common automated attacks but is NOT a substitute for
# proper input validation and parameterized queries in your application
if ($request_uri ~* "(%27|')(%20|\+|\s)*(or|and|union|select|insert|drop|delete|update|exec|execute)(%20|\+|\s)") {
return 403;
}
Path traversal prevention
# Block path traversal attempts: ../ or ..\ in raw or encoded form
if ($request_uri ~* "(\.|%2e)(\.|%2e)(/|%2f|\x5c|%5c)") {
return 403;
}
# Block double slash before wp-content
if ($request_uri ~* "//wp-content") {
return 403;
}
I kept this rule to the .. sequences that make a traversal. Characters like ~, | or ... are tempting to add, but once a rule sees the query string they turn up in ordinary search terms. The XSS rules below cover <script.
One side effect: because it tests $request_uri, the //wp-content rule sees the raw path before nginx merges slashes, so a site with misconfigured double-slash asset URLs will get 403s on those files. Fix the URLs before you turn it on.
File inclusion and CGI protection
# Block sensitive file extensions
location ~* \.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$ {
add_header X-Block-Reason "Sensitive File Extension" always;
return 444;
}
# Block CGI execution
location ~* \.(pl|cgi|py|sh|lua)$ {
add_header X-Block-Reason "CGI/Script Execution Not Allowed" always;
return 444;
}
Documentation and backup protection
# Block access to documentation files
location ~* "/(^$|readme|license|example|README|LEGALNOTICE|INSTALLATION|CHANGELOG)\.(txt|html|md)" {
add_header X-Block-Reason "Documentation File Protected" always;
deny all;
}
# Block access to backup files
location ~* "\.(old|orig|original|php#|php~|php_bak|save|swo|aspx?|tpl|sh|bash|bak?|cfg|cgi|dll|exe|git|hg|ini|jsp|log|mdb|out|sql|svn|swp|tar|rdf)$" {
add_header X-Block-Reason "Backup/Log File Protected" always;
deny all;
}
XSS and command injection protection
Important: Content-Security-Policy headers (configured above) are your primary XSS defense. The nginx rules below are supplementary blocking for obvious attack patterns.
# Block script tag injection attempts in the path or query string
# Catches common XSS patterns with URL encoding variations
if ($request_uri ~* "(<|%3c)(%20|\+|\s)*script.*?(>|%3e)") {
return 403;
}
# Block obvious event handler injection (onerror, onload, etc.)
if ($request_uri ~* "(%20|\+|\s)on\w+(%20|\+|\s)*(=|%3d)") {
return 403;
}
Unlike the location rules in this post, these don't set an X-Block-Reason header, because add_header isn't allowed inside a server-level if. Your access log still records each blocked request with status 403.
Note on command injection: Blocking shell metacharacters in nginx rules is generally not recommended as it can break legitimate URLs containing common characters like
:(ports, protocols),%(URL encoding), or;(query parameters). Implement command injection protection in your application layer with proper input validation and avoid shell execution where possible.
XML-RPC and brute-force mitigation
Attackers hammer WordPress through XML-RPC calls, login forms and arbitrary file uploads. Lock these down and automated tools can't exhaust your PHP workers or run unauthorized scripts.
Core file lockdown and XML-RPC blocking
# Block XML-RPC access
location ~* "xmlrpc.php" { deny all; }
location ~* "readme.txt" { deny all; }
# Protect sensitive WordPress directories
location ~* wp-admin/includes { deny all; }
location ~* wp-includes/theme-compat/ { deny all; }
location ~* wp-includes/js/tinymce/langs/.*\.php { deny all; }
# Block access to configuration files
location ~ /(\.|wp-config.php|readme.html|license.txt) { deny all; }
# Block temp files
location ~ ~$ { access_log off; log_not_found off; deny all; }
# Block archive files
location ~* ^/(wp-content)/(.*?)\.(text|txt|zip|gz|tar|bzip2|7z)$ { deny all; }
Upload directory isolation
# Block backup directories
location ~ ^/wp-content/uploads/sucuri { deny all; }
location ~ ^/wp-content/updraft { deny all; }
# Protect plugin/theme documentation
location ~* ^/wp-content/plugins/.+\.(txt|log|md)$ {
deny all;
error_page 403 =404 / ;
}
# Secure multisite uploads
location ~* ^/wp-content/uploads/sites/\d+/ {
try_files $uri $uri/ /index.php?$args;
location ~ \.php$ {
deny all;
}
}
# Block PHP execution in uploads
location ~* /wp-content/uploads/.*\.php$ {
deny all;
}
# Block restricted file types in uploads
location ~* ^/wp-content/uploads/.*.(html|htm|shtml|php|js|swf|css)$ {
add_header X-Block-Reason "Restricted Upload File Type" always;
deny all;
}
Rate limiting zones and endpoint throttling
To protect against abuse and DDoS attacks, set up strict rate limits:
# Define memory zones and rates for different request types
# Format: limit_req_zone $identifier zone=name:size rate=r/time_unit;
# General API requests
limit_req_zone $binary_remote_addr zone=general_api:10m rate=60r/m;
# Resource-intensive operations
limit_req_zone $binary_remote_addr zone=intensive_ops:10m rate=10r/m;
# Static file access
limit_req_zone $request_uri zone=static_files:10m rate=60r/s;
# Frontend requests
limit_req_zone $binary_remote_addr zone=frontend:10m rate=150r/m;
# Admin area requests
limit_req_zone $binary_remote_addr zone=admin:10m rate=600r/m;
This gives you a tiered approach: low rate (10r/m) for resource-intensive operations, medium (60r/m) for general API endpoints, high (150r/m) for frontend requests, very high (600r/m) for admin operations, and URI-based limiting (60r/s) for static resources.

Apply these limits in your location blocks:
# Example: Applying rate limits to different endpoints
# Resource-intensive endpoint
location /api/resource-heavy {
limit_req zone=intensive_ops burst=5 nodelay;
# ... rest of your configuration
}
# General API endpoint
location /api/ {
limit_req zone=general_api burst=10 nodelay;
# ... rest of your configuration
}
# Admin area
location /wp-admin/ {
limit_req zone=admin burst=20 nodelay;
# ... rest of your configuration
}
Microcaching under attack
When traffic spikes or distributed scanners hammer the site, serving straight from cache keeps the application responsive. If PHP and the database never run, they can't be starved.

Direct static file serving
Don't proxy static files to Apache. Serve them directly from nginx:
# Multilingual static asset handling
location ~* ^/(bn|np)?/.*\.(jpg|jpeg|png|gif|ico|css|js|svg|woff2)$ {
access_log off;
expires max;
add_header Cache-Control "public, no-transform";
add_header X-Static-File "true";
try_files $uri $uri/ =404;
}
This handles files for every language variant, caches aggressively, skips Apache completely for static content, and takes load off the server.
WordPress content optimization
# WordPress content handling
location ~* ^/(bn|np)?/wp-content/ {
access_log off;
expires max;
add_header Cache-Control "public, no-transform";
add_header X-Static-File "true";
try_files $uri $uri/ =404;
}
Dynamic microcache for traffic floods
For dynamic WordPress pages, short-lived microcaching absorbs concurrent burst requests for identical URLs. It's meant for anonymous traffic:
# Microcaching for dynamic pages during traffic spikes
fastcgi_cache_path /var/run/nginx-cache levels=1:2 keys_zone=WORDPRESS:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_cache_use_stale error timeout updating invalid_header http_500;
fastcgi_cache_valid 200 301 302 1s;
Logged-in users, recent commenters and password-protected posts should skip the cache, or one person's admin bar can end up in someone else's page. A map on the WordPress cookies handles that:
# http {} context: skip the cache when a WordPress session cookie is present
map $http_cookie $skip_cache {
default 0;
"~*wordpress_logged_in|comment_author|wp-postpass" 1;
}
# In the location that passes PHP to php-fpm
fastcgi_cache WORDPRESS;
fastcgi_cache_bypass $skip_cache;
fastcgi_no_cache $skip_cache;
Upstream buffer tuning
When requests do pass through to PHP-FPM or Apache, buffer configuration decides how worker connections behave. If buffers are undersized, slow clients or heavy response payloads can tie up backend workers.
Tuned buffers let nginx read the full backend response into memory quickly, hand the PHP worker back to the pool, and stream data to the client asynchronously:
# Upstream buffer tuning to protect PHP workers
proxy_buffering on;
proxy_buffer_size 16k;
proxy_buffers 16 16k;
proxy_busy_buffers_size 32k;
proxy_temp_file_write_size 64k;
# FastCGI buffer tuning when using direct PHP-FPM
fastcgi_buffering on;
fastcgi_buffer_size 16k;
fastcgi_buffers 16 16k;
fastcgi_busy_buffers_size 32k;
fastcgi_temp_file_write_size 64k;
With buffers sized to standard WordPress HTML payloads, upstream processes don't wait on slow clients.
Dealing with bounty hunters and security scanners
One persistent challenge for high-traffic sites is the load from bug bounty hunters and automated scanners. Popular websites attract automated vulnerability scans, security researchers poking for issues, and penetration testing tools running nonstop.
All of that creates significant server load and sometimes hurts site performance. The rules above help by blocking malicious patterns at nginx, before they reach the application server. Fewer resources wasted, better response times for real users.
Expected results
After implementing these security measures, you should see:
- Reduced attack surface: Common attack vectors blocked before they reach your application
- Better performance: Blocking malicious requests early in the cycle keeps response times stable
- Lower server load: Bad bots and attacks handled at the nginx level, not the application layer
- Quieter application logs: Blocked requests stop at nginx, so they don't add noise to your PHP and WordPress error logs
The configurations come from production environments serving thousands of users daily.
Testing and verification
Here's a template for testing your security implementation:
Basic access testing
# Test homepage access
curl -I https://your-domain.com/
# Test subsite access (if using multisite)
curl -I https://your-domain.com/site1/
curl -I https://your-domain.com/site2/
Security rule testing
# Test file execution protection
curl -I "https://your-domain.com/wp-content/uploads/test.php"
curl -I "https://your-domain.com/wp-content/themes/test.php"
# Test SQL injection protection (expect 403)
curl -I "https://your-domain.com/?id=1%27%20or%201=1"
curl -I "https://your-domain.com/?user=admin%27%20union%20select"
# Test XSS protection (expect 403)
curl -I "https://your-domain.com/?s=%3Cscript%3Ealert(1)%3C/script%3E"
# Test path traversal protection (expect 403)
curl -I --path-as-is "https://your-domain.com/wp-content/plugins/../../etc/passwd"
curl -I "https://your-domain.com/?file=..%2f..%2fwp-config.php"
# Test sensitive file protection
curl -I "https://your-domain.com/wp-config.php"
curl -I "https://your-domain.com/.env"
Rate limit testing
# Function to test rate limits
test_rate_limit() {
local endpoint=$1
local requests=$2
local delay=${3:-0}
echo "Testing rate limit for $endpoint"
for i in $(seq 1 $requests); do
curl -I "$endpoint" &>/dev/null
echo -n "."
sleep $delay
done
echo "Done!"
# Final request to check if rate limit is triggered
curl -I "$endpoint"
}
# Example usage:
# test_rate_limit "https://your-domain.com/api/" 100 0.1
# test_rate_limit "https://your-domain.com/wp-admin/" 50 0.2
Bot detection testing
# Test with different User-Agents
curl -I -A "Googlebot/2.1 (+http://www.google.com/bot.html)" https://your-domain.com/
curl -I -A "facebookexternalhit/1.1" https://your-domain.com/
curl -I -A "Mozilla/5.0 (compatible; Bingbot/2.0)" https://your-domain.com/
Keep in mind: curl collapses ../ segments before it sends the request, so without --path-as-is the path traversal test would just request /etc/passwd and never trip the rule. The flag keeps the raw ../ on the wire.
Remember to:
- Replace
your-domain.comwith your actual domain - Adjust request numbers and delays based on your rate limits
- Test from different IP addresses to verify IP-based limits
- Run tests in a staging environment first
- Monitor logs while testing to verify proper blocking
Maintenance best practices
To keep your security implementation effective:
- Monitor logs: Regularly check nginx access logs for 403 and 444 responses, and error logs for requests refused by
denyrules - Update rules: Keep security rules current with new threat patterns
- Test after updates: Verify security measures after WordPress core/plugin updates
- Review rate limits: Adjust rate limiting based on traffic patterns
- Audit bot access: Monitor and update bot detection patterns
Defense-in-depth model
Security layers between attacker and WordPress application:
| Layer | Protection | Components |
|---|---|---|
| Transport security | Encrypt and hide server info | HSTS (force HTTPS), TLS 1.2+ only, server_tokens off |
| Rate limiting | Throttle excessive requests | 60r/m general API, 10r/m intensive ops, burst handling with nodelay |
| Input filtering | Block malicious payloads | SQL injection patterns, XSS script tags, path traversal (../) |
| Access control | Restrict sensitive paths | Block xmlrpc.php, protect wp-config.php, deny hidden files (.git, .env), block PHP in /uploads/ |
| Response headers | Harden browser behavior | Content-Security-Policy, X-Frame-Options: SAMEORIGIN, X-Content-Type-Options: nosniff |
Outcomes:
- Malicious requests Blocked or Blocked/Logged
- Legitimate requests Protected App
The takeaway: adapt these configurations to your own site, and test them regularly.
Frequently asked questions
- How do I protect a high-traffic WordPress site with Nginx?
- Drop bad requests at Nginx before they reach PHP or the database. Layer security headers, edge filtering, XML-RPC and file blocks, rate limiting, microcaching and upstream buffer tuning, so scanners and brute-force attempts do not exhaust php-fpm workers.
- How do I block XML-RPC in WordPress with Nginx?
- Add a location block for xmlrpc.php with deny all. In the same layer I also block wp-config.php, hidden files and PHP execution inside wp-content/uploads.
- How do I rate limit WordPress with Nginx?
- Define limit_req_zone zones per request type and apply them with limit_req. My tiers are 10 requests per minute for intensive operations, 60 for general API, 150 for frontend and 600 for the admin area.
- Are Nginx SQL injection regex rules enough?
- No. Regex rules at the nginx level are a defense-in-depth measure that can produce false positives and be bypassed with encoding. Parameterized queries stay your primary defense, and Content-Security-Policy is the main XSS defense.
Related posts
- A deterministic prompt injection filter for agents that read my email
Cleaning out 26 spam emails led to a stdlib-only Python filter with 45 tests that catches homoglyphs, hidden tags and Base64 or ROT13 payloads before Hermes reads mail.
- pmharden: auditing npm, pnpm and yarn config for secrets
pmharden audits package manager config, scans for plaintext tokens and flags risky global packages in one command. A walkthrough of the code, the 45 tests and the rough edges I still see.
- A WordPress plugin that throttles Facebook's link-preview crawler
Facebook's crawler had a friend's shared host threatening suspension. The plugin throttles each URL, answers 429 with Retry-After and lets images through.