Home › Blog › Article

Running WordPress on Nginx: Rules, Security Headers and Directory Guards

Running WordPress on Nginx: Rules, Security Headers and Directory Guards

Answer first: what a correct Nginx WordPress configuration does

A correct Nginx WordPress configuration sends unknown clean URLs to index.php with try_files, serves real static files directly, blocks PHP execution inside wp-content/uploads, adds a tested baseline of security headers, and applies explicit guards around xmlrpc.php and wp-login.php. You know it is done right when nginx -t passes, permalinks and static assets return 200, a PHP test file in uploads is denied or downloaded as inert text, response headers match your checklist, and blocked endpoints behave as designed while legitimate admin, REST, cron and WooCommerce traffic still works.

This tutorial assumes Ubuntu 24.04 LTS or Debian 12, Nginx 1.24+ or 1.26+, PHP-FPM 8.2 or 8.3, WordPress 6.7+ in 2026, and a site root such as /var/www/example.com/public. Replace example.com, the PHP socket path and the Unix user with your real values. Work from a staging clone first; if you are moving changes through environments, align this with From Staging to Production: Release Flow and Data Sync so config and database changes ship together.

Preparation Process: snapshot, inventory and a safe rollback point

  1. Create a timestamped backup of the server block, snippets and WordPress files: sudo mkdir -p /root/nginx-wp-2026-backup && sudo cp -a /etc/nginx/sites-available/example.com /etc/nginx/snippets /root/nginx-wp-2026-backup/ && sudo tar -czf /root/nginx-wp-2026-backup/wp-files.tgz -C /var/www/example.com public.
  2. Record the active config with sudo nginx -T > /root/nginx-wp-2026-backup/nginx-T-before.txt, then note the PHP-FPM socket using grep -R 'listen =' /etc/php/8.3/fpm/pool.d/.
  3. Capture a baseline with curl -sS -o /dev/null -w '%{http_code} %{content_type}n' https://example.com/, a known post, an image, /wp-login.php, /xmlrpc.php and /wp-json/.
  4. Confirm WordPress permalink structure in Settings → Permalinks, and list existing .htaccess-equivalent behaviour, CDN rules, object-cache drop-ins and WAF rules that may already rewrite or block URLs.
  5. Open a second root shell or console session so a bad reload does not lock you out, and schedule a maintenance window if the site has checkout traffic.
  6. Keep a one-command rollback ready: sudo cp -a /root/nginx-wp-2026-backup/sites-available/example.com /etc/nginx/sites-available/example.com && sudo nginx -t && sudo systemctl reload nginx.

Why this matters: Nginx does not read .htaccess, so every rewrite, deny and header decision lives in the server block. A single misplaced location can turn uploads into 404s, break wp-admin, or worse, hand a PHP file to the wrong handler. Before editing, also confirm DNS and hostnames are stable; our WordPress Domain Configuration: Vendor Evaluation Guide is useful when the server block and domain vendor settings disagree. For teams that want a reviewed baseline rather than patching production live, Custom WordPress Development can include the server config, deploy script and regression tests as one deliverable.

Step 1: rewrites and try_files

Write the canonical server block

Create /etc/nginx/sites-available/example.com with one PHP upstream and one front-controller rule. The goal is ordering: exact static files win, directories resolve to their index, and only missing paths fall through to WordPress. Do not add a broad rewrite ^ /index.php last;; that is the classic cause of double rewrites, lost query strings and wp-admin redirect loops in 2026 WordPress builds.

upstream wp_php_83 {
    server unix:/run/php/php8.3-fpm.sock;
}

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    root /var/www/example.com/public;
    index index.php index.html;

    # Keep the original query string intact for front-controller routing.
    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ .php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass wp_php_83;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_read_timeout 60s;
    }

    location ~* .(?:js|css|png|jpg|jpeg|gif|webp|avif|svg|ico|woff2?|ttf|eot|mp4|pdf)$ {
        try_files $uri =404;
        expires 30d;
        add_header Cache-Control 'public, immutable' always;
        access_log off;
    }

    location = /favicon.ico { log_not_found off; access_log off; }
    location = /robots.txt  { try_files $uri =404; access_log off; }
}

Why /index.php?$args instead of /index.php?$query_string: both work in modern Nginx, but $args is the canonical variable used by the official WordPress Nginx guidance and keeps POST query parameters, preview links, ?p=, ?s= and WooCommerce filter URLs intact. If you use a subdirectory install, change the fallback to /blog/index.php?$args and keep the root pointing at the webroot, not at /blog.

Apply and verify routing

Run sudo ln -sfn /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/example.com, then sudo nginx -t and sudo systemctl reload nginx. Verify with curl -I https://example.com/sample-post/, curl -I 'https://example.com/?p=123', curl -I https://example.com/wp-content/themes/my-theme/style.css and curl -I https://example.com/wp-json/. Expect 200 for real content, 200 or 301 for the query URL depending on canonical redirects, and 404 for a missing image. Inspect /var/log/nginx/error.log for rewrite or internal redirection cycle.

Common pitfalls: a regex location ~ .php placed before a more specific uploads guard will win; try_files $uri $uri/ /index.php without ?$args breaks search and previews; and a CDN page rule that strips query strings will make correct Nginx look broken. Rollback is the copied server block from preparation, followed by nginx -t && systemctl reload nginx. If only permalinks fail, re-save Settings → Permalinks once to flush rewrite rules, then re-test before touching Nginx again. See the WordPress Nginx documentation for the upstream reference.

Step 2: disabling PHP in uploads

Add a directory guard that beats the PHP handler

Get a Quote

Email + requirement + budget range — we reply with a quote within 24 hours.

Uploads are the only WordPress directory that must accept writes from the application and still never execute code. Create /etc/nginx/snippets/wp-uploads-guard.conf and include it before the general PHP location in the server block. The nested PHP location is deliberate: Nginx picks the longest matching prefix, then the nested regex denies the file before fastcgi_pass ever sees it.

# /etc/nginx/snippets/wp-uploads-guard.conf
location ^~ /wp-content/uploads/ {
    # Allow media, but never interpret a file as PHP.
    location ~ .php(?:[0-9]+)?$ {
        deny all;
        return 403;
    }

    location ~* .(?:php[0-9]?|phtml|phar|pht|phps|cgi|pl|py|sh)$ {
        deny all;
        return 403;
    }

    try_files $uri =404;
    add_header X-Content-Type-Options 'nosniff' always;
    add_header Content-Disposition 'inline' always;
    access_log off;
}

# Also stop dotfiles and backup/source dumps that plugins sometimes leave behind.
location ~* ^/wp-content/uploads/.*(?:.|~)(?:htaccess|env|sql|zip|tar|gz|log|bak|old|swp)$ {
    deny all;
    return 403;
}

Include it with include snippets/wp-uploads-guard.conf; immediately above location ~ .php$. If you run multisite, add the same guard for /wp-content/blogs.dir/ and any legacy /files/ rewrite. If an object-storage plugin offloads media, keep the guard anyway: it protects the local fallback path used during sync and imports.

Verify with a harmless probe file

Run printf '<?php echo "probe"; ?>' | sudo tee /var/www/example.com/public/wp-content/uploads/_nginx_probe.php >/dev/null, then curl -i https://example.com/wp-content/uploads/_nginx_probe.php. A correct setup returns 403 and the body never contains probe. Also test _nginx_probe.phtml, _nginx_probe.php7 and /wp-content/uploads/.env. Delete the probes with sudo rm -f /var/www/example.com/public/wp-content/uploads/_nginx_probe.* and confirm a real image still returns 200 image/webp or image/jpeg.

Why this is stronger than a filesystem permission change alone: chmod 644 stops direct CLI execution but not FastCGI, and php-fpm often runs as the same user that owns uploads. Common pitfalls include putting the guard after the global PHP regex, using location /uploads/ instead of the full /wp-content/uploads/ prefix, and returning 404 for all uploads because try_files was omitted. If media breaks, comment out only the include line, reload, and compare nginx -T | grep -n uploads against the backup. Do not remove the guard permanently; fix the prefix instead.

Step 3: security headers checklist

Build one snippet and apply it consistently

Headers belong in a single snippet included in both HTTP and HTTPS server blocks, with always so they survive 403, 404 and 304 responses. Create /etc/nginx/snippets/wp-security-headers.conf. In 2026, use Strict-Transport-Security only after HTTPS is stable, keep Content-Security-Policy in Report-Only first, and avoid X-XSS-Protection because modern browsers ignore it and legacy values can reintroduce filtering bugs.

# /etc/nginx/snippets/wp-security-headers.conf
add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains; preload' always;
add_header X-Content-Type-Options 'nosniff' always;
add_header X-Frame-Options 'SAMEORIGIN' always;
add_header Referrer-Policy 'strict-origin-when-cross-origin' always;
add_header Permissions-Policy 'camera=(), microphone=(), geolocation=(), payment=(self), usb=(), interest-cohort=()' always;
add_header Cross-Origin-Opener-Policy 'same-origin' always;
add_header Cross-Origin-Resource-Policy 'same-origin' always;
add_header Content-Security-Policy-Report-Only "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'self'; img-src 'self' data: https:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https:; style-src 'self' 'unsafe-inline' https:; font-src 'self' data: https:; connect-src 'self' https:; report-uri /csp-report" always;

# Do not leak the exact Nginx or PHP version on error pages.
server_tokens off;
fastcgi_hide_header X-Powered-By;

Include it inside the server { } block with include snippets/wp-security-headers.conf;. If your admin uses the block editor, Gutenberg still relies on inline styles and some inline scripts in WordPress 6.7+, so the Report-Only policy above is intentionally permissive. After 7 days of clean reports, tighten script-src with nonces generated by your theme or a trusted plugin, then promote the header from Content-Security-Policy-Report-Only to Content-Security-Policy. If you serve embeds, change X-Frame-Options to ALLOW-FROM is not valid in 2026; use frame-ancestors in CSP instead and drop the legacy header only after testing oEmbed.

Checklist and verification table

HeaderExpected 2026 valueHow to verifyRollback trigger
HSTSmax-age=31536000; includeSubDomains; preloadcurl -sSI https://example.com/ | grep -i strictAny subdomain still HTTP-only; remove includeSubDomains first, never preload-submit early.
X-Content-Type-Optionsnosniffcurl -sSI https://example.com/wp-content/uploads/logo.png | grep -i nosniffLegacy plugin serving wrong MIME; fix MIME, do not remove header.
X-Frame-Options / CSP frame-ancestorsSAMEORIGIN / 'self'Load /wp-admin/post-new.php and one oEmbed previewEditor iframe blank; move to Report-Only CSP and keep SAMEORIGIN.
Referrer-Policystrict-origin-when-cross-origincurl -sSI https://example.com/ | grep -i referrerAffiliate plugin needs full path; scope an exception to that route.
Permissions-PolicyDeny camera, mic, geo, usb; allow payment=(self)DevTools → Application → PermissionsCheckout payment iframe fails; add the PSP origin explicitly.
COOP / CORPsame-originCross-origin image and OAuth callback testSSO popup breaks; use same-origin-allow-popups on COOP only.
Server tokens / X-Powered-ByNo version stringcurl -sSI https://example.com/nope | grep -Ei 'server|x-powered'None; this is safe to keep.

Common pitfalls: duplicate add_header directives in a nested location silently replace all parent headers in that location, so keep the uploads guard limited to X-Content-Type-Options and Content-Disposition or re-include the full snippet there. A CDN can overwrite headers at the edge; compare origin via curl --resolve example.com:443:ORIGIN_IP before blaming Nginx. Rollback is one commented include line plus sudo nginx -t && sudo systemctl reload nginx; HSTS is the one change that can persist in browsers, so lower max-age to 300 for a day before removing it entirely.

Step 4: xmlrpc and login endpoints

Decide the policy before writing the rule

xmlrpc.php is still shipped in WordPress 6.7+ for legacy clients, pingbacks and some mobile editors, but most 2026 sites should use the REST API instead. wp-login.php must stay reachable for humans, password resets and wp-admin redirects; blocking it by IP without an allowlist is the fastest way to lock out a distributed agency team. Add /etc/nginx/snippets/wp-endpoint-guards.conf and include it near the top of the server block, before the front controller.

# /etc/nginx/snippets/wp-endpoint-guards.conf

# 1) Default-deny xmlrpc, with an explicit opt-in allowlist.
location = /xmlrpc.php {
    allow 203.0.113.42;      # replace with your office or Jetpack egress IP
    deny all;
    access_log /var/log/nginx/wp-xmlrpc.log;
    # If no IP needs it, replace the two lines above with: return 403;
}

# 2) Rate-limit login POSTs. Define the zone once in http{} context:
#    limit_req_zone $binary_remote_addr zone=wplogin:10m rate=6r/m;
location = /wp-login.php {
    limit_req zone=wplogin burst=3 nodelay;
    limit_req_status 429;
    include snippets/fastcgi-php.conf;
    fastcgi_pass wp_php_83;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
    access_log /var/log/nginx/wp-login.log;
}

# 3) Never expose install/upgrade internals or config backups.
location ~* ^/(?:wp-config.php|wp-config.bak|readme.html|license.txt|wp-admin/install.php|wp-admin/upgrade.php)$ {
    deny all;
    return 403;
}

# 4) admin-ajax and REST stay untouched on purpose.
location = /wp-admin/admin-ajax.php {
    include snippets/fastcgi-php.conf;
    fastcgi_pass wp_php_83;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

Add limit_req_zone $binary_remote_addr zone=wplogin:10m rate=6r/m; inside /etc/nginx/nginx.conf under the http { } block, not inside the server block, or Nginx will fail nginx -t with limit_req_zone is not allowed here. If you use Jetpack, WooCommerce mobile app or a legacy desktop editor, keep the allowlist and confirm the current egress IPs in 2026 rather than allowing all of xmlrpc.php. For everything else, return 403; is cleaner and cheaper. Do not block /wp-json/ or admin-ajax.php; the block editor, heartbeat, contact forms and checkout all depend on them. The WordPress REST API handbook is the reference when replacing an old XML-RPC integration.

Verify behaviour, then roll back precisely

Run sudo nginx -t && sudo systemctl reload nginx. From a non-allowlisted IP, curl -i -X POST https://example.com/xmlrpc.php should return 403; from the allowlisted host it should reach PHP. Simulate login pressure with for i in $(seq 1 10); do curl -s -o /dev/null -w '%{http_code} ' -d 'log=test&pwd=test' https://example.com/wp-login.php; done and expect a mix of 200 and 429, not 502. Then log in normally, reset a password, save a Gutenberg post and submit an AJAX form. Watch tail -f /var/log/nginx/wp-login.log /var/log/nginx/error.log.

Common pitfalls: putting limit_req_zone in the wrong context, forgetting that a CDN makes every request share one $binary_remote_addr, and denying wp-login.php outright so wp-admin redirects loop. If the CDN is in front, restore real client IPs with set_real_ip_from and real_ip_header X-Forwarded-For before rate limiting. Rollback order: comment out only the endpoint snippet include, reload, re-test login, then re-enable one guard at a time. Keep the wp-config.php deny rule even during rollback; it has no legitimate traffic cost.

Validation: a repeatable 2026 acceptance run

Validation: a repeatable 2026 acceptance run

Save this as /root/nginx-wp-2026-backup/verify.sh and run it after every deploy. It is the difference between ‘the config loaded’ and ‘the site still works’.

#!/usr/bin/env bash
set -u
H='https://example.com'
for u in '/' '/sample-post/' '/?s=nginx' '/wp-json/' '/wp-login.php' 
         '/wp-content/uploads/logo.webp' '/wp-content/uploads/_gone.php' 
         '/xmlrpc.php' '/wp-config.php' '/missing-image.png'; do
  printf '%-46s ' "$u"
  curl -sS -o /dev/null -w '%{http_code} %{content_type}n' "$H$u"
done
echo '--- headers ---'
curl -sSI "$H/" | grep -Ei 'strict-transport|content-type-options|frame-options|referrer-policy|permissions-policy|content-security|server:'
echo '--- config ---'
sudo nginx -t 2>&1 | tail -1

Expected matrix: /, post, search, REST, login and the real image are 200; _gone.php, wp-config.php and xmlrpc.php from an untrusted IP are 403; the missing image is 404 with nosniff still present; nginx -t ends with test is successful. Run the same script against origin with curl --resolve and against the CDN hostname, then diff the two header sets. If they differ, fix the edge rule rather than adding a second add_header at origin.

Also verify PHP-FPM separately: sudo php-fpm8.3 -t, systemctl status php8.3-fpm, and a deliberate 404 to confirm no X-Powered-By leaks. For release days, pair this script with WordPress Backup Vendor Decisions for 2026 so a config rollback and a file/database restore are tested in the same window. Store the output next to the deploy tag; it becomes evidence for clients and for your own post-incident review.

Rollback: exact commands and decision tree

Rollback is not ‘undo everything’. Use the smallest reversible change that restores traffic. If nginx -t fails, do not reload; Nginx keeps serving the last valid in-memory config, so fix the syntax first with sudo nginx -T | less. If reload succeeded but pages 404, restore only the server block. If headers break an embed, comment only the header snippet. If uploads 403, check the guard prefix before disabling it. If login 429s for everyone, remove the rate limit but keep the wp-config.php deny.

# Full config rollback
sudo cp -a /root/nginx-wp-2026-backup/sites-available/example.com /etc/nginx/sites-available/example.com
sudo cp -a /root/nginx-wp-2026-backup/snippets/. /etc/nginx/snippets/
sudo nginx -t && sudo systemctl reload nginx

# Targeted rollback examples
sudo sed -i 's|^s*include snippets/wp-security-headers.conf;|# include snippets/wp-security-headers.conf;|' /etc/nginx/sites-available/example.com
sudo sed -i 's|^s*include snippets/wp-endpoint-guards.conf;|# include snippets/wp-endpoint-guards.conf;|' /etc/nginx/sites-available/example.com
sudo nginx -t && sudo systemctl reload nginx

# Compare before/after and prove what changed
diff -u /root/nginx-wp-2026-backup/nginx-T-before.txt <(sudo nginx -T) | head -80
sudo tail -n 50 /var/log/nginx/error.log

After rollback, re-run verify.sh and clear any CDN cache with a targeted purge, not a full purge during peak traffic. If HSTS was live with a long max-age, publish a temporary max-age=300 header for at least one full browser session before removing it; otherwise visitors keep the old policy locally. Document the trigger, the reverted include and the failing curl line in the deploy log. That record is what turns a 2026 incident into a permanent regression test instead of a repeat surprise.

Frequently asked questions

Does Nginx still need .htaccess for WordPress in 2026?

No. Nginx never reads .htaccess. Put permalink fallbacks, denies and headers in the server block or included snippets. Keep an .htaccess file only if the same docroot is also served by Apache during a migration, and remove it after cutover to avoid two sources of truth.

Will blocking xmlrpc.php break Jetpack or the WordPress mobile app?

It can. Modern Jetpack and the 2026 mobile apps prefer /wp-json/, but some legacy flows still call XML-RPC. Start with the IP allowlist and watch /var/log/nginx/wp-xmlrpc.log for 7 days before switching to return 403;. Never block admin-ajax.php or REST as a shortcut.

Why do my security headers disappear on 403 and 404 responses?

Because a nested location with its own add_header replaces all inherited headers, and headers without always are omitted on errors. Use always on every directive and re-include the header snippet inside guarded locations, or keep guarded locations limited to one or two explicit headers.

Action checklist

  • Snapshot nginx -T, the server block, snippets and WordPress files into /root/nginx-wp-2026-backup/ before any edit.
  • Deploy try_files $uri $uri/ /index.php?$args;, then verify permalinks, query strings, static assets and REST.
  • Include the uploads guard before the PHP handler and prove a probe .php returns 403 with no executed output.
  • Ship the header snippet with always, keep CSP in Report-Only for 7 days, and diff origin versus CDN headers.
  • Run verify.sh after every reload and keep the one-line targeted rollback commands in the deploy runbook.

Need a reviewed Nginx WordPress configuration, regression tests and a deploy runbook for your team? Our engineers audit production server blocks and ship fixes with rollback included. Explore Custom WordPress Development or browse the technical column index and services page.

“, “faq”: [ { “question”: “Does Nginx still need .htaccess for WordPress in 2026?”, “answer”: “No. Nginx never reads .htaccess. Put permalink fallbacks, denies and headers in the server block or included snippets, and remove any Apache-only file after migration.” }, { “question”: “Will blocking xmlrpc.php break Jetpack or the WordPress mobile app?”, “answer”: “It can for legacy flows. Start with an IP allowlist and log review for 7 days, keep /wp-json/ and admin-ajax.php open, then switch to return 403 only if no trusted client needs XML-RPC.” }, { “question”: “Why do security headers disappear on 403 and 404 responses?”, “answer”: “Nested locations with their own add_header replace inherited headers, and directives without always are skipped on errors. Add always everywhere and re-include the header snippet in guarded locations.” } ], “cover”: “Modern flat technical illustration of a layered web server stack: a calm teal Nginx gateway shield routing clean URL arrows into a WordPress core block, guarded upload folder with a locked PHP file, floating header tags and endpoint gates, subtle grid, no text, letters, numbers, logos or watermarks.

References & further reading

Need WordPress Development?

Free proposal and quote within 24 hours — we serve clients worldwide.

QQ