Most hacked WordPress sites we clean up weren't hit by anything clever. A plugin sat unpatched for months, PHP ran straight from the uploads folder, or the admin password was the same one used everywhere else. Then the attacker drops a web shell, injects spam links or an iframe, and the business finds out from Google or from a customer. Good server security closes those doors before anyone tries them.
This guide is the checklist we apply to self-hosted WordPress. Every config and command below was tested on WordPress 7.1 with PHP 8.5, nginx 1.30, Apache 2.4 and MariaDB. Paths assume Ubuntu with the site in /var/www/example.com/public. On Ubuntu 24.04 replace 8.5 with 8.3 in PHP paths.
The checklist
- Keep core, plugins and themes updated, and delete what you don't use.
- Make the code read-only for PHP and update through WP-CLI or CI, not FTP.
- Set file ownership and permissions so PHP can write only to uploads.
- Move
wp-config.phpabove the web root, lock it to640and setDISALLOW_FILE_EDIT. - Give the database user rights on one database only.
- Block PHP execution in uploads and deny access to hidden, backup and log files.
- Turn off XML-RPC unless something needs it.
- Rate limit
wp-login.phpand turn on two-factor authentication for admins. - Hide usernames from the REST API, author scans and the users sitemap.
- Send security headers and force HTTPS.
- Hide PHP and server versions, disable dangerous PHP functions.
- Take backups you have actually restored.
- Watch file integrity and put a WAF in front of the site.
The sections below show how to do each one and how to check that it works.
1. Keep WordPress, plugins and themes updated
Almost every compromised WordPress site we see runs a plugin with a known, already patched vulnerability. Hardening reduces the damage, but only an update closes the hole. Delete plugins and themes you don't use: a deactivated plugin is still a PHP file an attacker can request directly.
There are two sane ways to keep a site updated. Pick one per site.
Option A. Let WordPress update itself
This fits a small site on a single server with nobody deploying code. Minor core releases (security and maintenance) install automatically by default. Turn on automatic updates for plugins and themes too:
shell
1wp plugin auto-updates enable --all2wp theme auto-updates enable --allThe catch: to update itself, WordPress needs PHP to own the code. That means a PHP-level bug can also rewrite your plugins. If you go this way, at least turn off the built-in file editor with DISALLOW_FILE_EDIT (section 3), block PHP in uploads (section 5) and watch file integrity (section 13).
Option B. Read-only code, updates from WP-CLI or CI
This is what we use for business sites. A separate deploy user owns the code, PHP (the www-data user) can only read it, and the dashboard can't install or update anything:
php
1define( 'DISALLOW_FILE_EDIT', true );2define( 'DISALLOW_FILE_MODS', true );DISALLOW_FILE_MODS removes plugin and theme installs, updates and deletion from the dashboard, and it also turns off automatic updates. Admins can still activate and deactivate plugins that are already installed. Updates now run as the deploy user, from a CI job or on a schedule:
shell
1sudo -u deploy -i -- sh -c 'cd /var/www/example.com/public && wp core update && wp core update-db && wp plugin update --all && wp theme update --all && wp language core update'To see what's pending before you update:
shell
1wp core check-update2wp plugin list --update=availableWP-CLI works with DISALLOW_FILE_MODS set: in our test wp plugin install and wp plugin update --all ran fine while the same actions were gone from the dashboard. Because the dashboard can't update anything, someone has to own the schedule. Run updates at least weekly and the same day for security releases. If the site runs on several servers, this is the only option that keeps them in sync: we explain why in our guide to a scalable WordPress environment on AWS.
With read-only code you can also move WP-Cron to a real cron job, so scheduled tasks don't depend on visitors. Add define( 'DISABLE_WP_CRON', true ); to wp-config.php and this line to the deploy user's crontab:
shell
1*/5 * * * * cd /var/www/example.com/public && wp cron event run --due-now --quietWhy not update over FTP
Many hardening guides still tell you to run a local FTP server, so WordPress can update itself while the files stay owned by another user. We don't recommend it.
When WordPress can't write to its own files, it doesn't update directly. It falls back to FTP: in our test with read-only code, get_filesystem_method() returned ftpsockets, and the dashboard asked for FTP credentials. To make that work without a prompt, the FTP password goes into wp-config.php. That's the problem: wp-config.php must be readable by PHP, so any code running in PHP can read the FTP password and use it to rewrite the same files. The separation is gone, and you've added another service to patch, often without TLS. Plain FTP also sends the password unencrypted.
Read-only code with WP-CLI updates gives you the same goal without the hole: PHP never holds credentials that can change the code.
2. Set file ownership and permissions
The rule is simple: PHP reads everything and writes only to uploads. The first command moves wp-config.php one level above the web root (section 3 explains why). Run as root:
shell
1sudo mv /var/www/example.com/public/wp-config.php /var/www/example.com/wp-config.php2sudo chown -R deploy:www-data /var/www/example.com3sudo find /var/www/example.com -type d -exec chmod 755 {} +4sudo find /var/www/example.com -type f -exec chmod 644 {} +5sudo chmod 640 /var/www/example.com/wp-config.php6sudo chown -R www-data:www-data /var/www/example.com/public/wp-content/uploadsThe result, checked with stat:
shell
1deploy:www-data 640 wp-config.php2deploy:www-data 755 public3deploy:www-data 644 public/index.php4deploy:www-data 755 public/wp-content5www-data:www-data 755 public/wp-content/uploadsPHP can read wp-config.php through the group, other local users can't read it at all, and an attempt to write a file as www-data anywhere outside uploads ends with Permission denied. Some cache and backup plugins need their own folder in wp-content (for example wp-content/cache). Give www-data that one folder, not the whole wp-content.
If you chose option A, PHP needs to own the code instead: sudo chown -R www-data:www-data /var/www/example.com/public. Keep wp-config.php owned by deploy with mode 640 either way.
3. Lock down wp-config.php
wp-config.php holds the database password and the secret keys, so treat it like a private key.
Move it out of the web root. WordPress looks for wp-config.php in its own folder and one level up. With the site in /var/www/example.com/public, the mv in section 2 put it in /var/www/example.com/wp-config.php, where the web server can't serve it even if PHP stops working. WordPress and WP-CLI both find it there without any extra settings. If your layout doesn't allow this, the web server rules in section 5 deny access to it anyway.
Add the hardening constants. Put them above the line /* That's all, stop editing! */:
php
1define( 'DISALLOW_FILE_EDIT', true );2define( 'DISALLOW_FILE_MODS', true );3define( 'FORCE_SSL_ADMIN', true );4define( 'WP_DEBUG', false );5define( 'WP_DEBUG_DISPLAY', false );DISALLOW_FILE_EDIT removes the theme and plugin file editor. Without it, anyone who steals an admin session can paste PHP code into a theme file from the browser. With it, in our test theme-editor.php and plugin-editor.php answered Sorry, you are not allowed to access this page and the editor disappeared from the menu. Use DISALLOW_FILE_MODS only with option B from section 1. FORCE_SSL_ADMIN keeps logins and the dashboard on HTTPS.
Use unique salts. The keys and salts sign login cookies. Generate fresh ones on install, and again after any incident: it logs out every user, including an attacker with a stolen cookie.
shell
1wp config shuffle-salts4. Give the database user only what WordPress needs
Each site gets its own database and its own user, limited to that database and to the host it connects from:
shell
1CREATE DATABASE wp_example CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;2CREATE USER 'wp_example'@'localhost' IDENTIFIED BY 'a-long-random-password';3GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, DROP ON wp_example.* TO 'wp_example'@'localhost';No global privileges, no FILE, no GRANT OPTION. In our test this user got Access denied when it tried to read the mysql.user table, create another database or write a file with SELECT ... INTO OUTFILE. An SQL injection in a plugin then stays inside one site's data.
You could go further and leave only SELECT, INSERT, UPDATE, DELETE, but core upgrades and many plugins change tables, and they break without CREATE and ALTER. If you do split privileges, run upgrades with a separate user and keep tested backups.
5. Harden the web server
The web server is where you stop the most common attack after a vulnerable plugin: a PHP file uploaded into wp-content/uploads and then opened in a browser. Without a rule, it runs. In our test a file shell.php in uploads printed EXECUTED on both nginx and Apache until the rules below were added.
nginx
Rate limiting for the login page lives in the http context, so put it in its own file, /etc/nginx/conf.d/wp-login-limit.conf:
nginx
1# Count only POST requests to wp-login.php: an empty key is not limited.2map $request_method $wp_login_key {3 POST $binary_remote_addr;4 default "";5}6limit_req_zone $wp_login_key zone=wp_login:10m rate=10r/m;The site config, for example /etc/nginx/sites-available/example.com:
nginx
1server {2 listen 80;3 server_name example.com;4 return 301 https://$host$request_uri;5}6
7server {8 listen 443 ssl;9 server_name example.com;10 root /var/www/example.com/public;11 index index.php;12
13 ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;14 ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;15
16 server_tokens off;17 client_max_body_size 64m;18
19 add_header Strict-Transport-Security "max-age=31536000" always;20 add_header X-Content-Type-Options "nosniff" always;21 add_header X-Frame-Options "SAMEORIGIN" always;22 add_header Referrer-Policy "strict-origin-when-cross-origin" always;23 add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;24
25 location / {26 try_files $uri $uri/ /index.php?$args;27 }28
29 # Hidden files and folders (.git, .env, .htaccess), except ACME challenges30 location ~ /\.(?!well-known/) {31 deny all;32 }33
34 # Backups, dumps, logs and files that give away the WordPress version35 location ~* \.(bak|old|orig|save|swp|sql|log|dist)$ {36 deny all;37 }38 location ~* ^/(readme\.html|license\.txt|wp-config\.php|wp-config-sample\.php)$ {39 deny all;40 }41
42 location = /xmlrpc.php {43 deny all;44 }45
46 # No PHP execution in uploads. Must come before the \.php$ block.47 location ~* ^/wp-content/uploads/.*\.(php|phtml|phar)$ {48 deny all;49 }50
51 location = /wp-login.php {52 limit_req zone=wp_login burst=5 nodelay;53 limit_req_status 429;54 include fastcgi_params;55 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;56 fastcgi_pass unix:/run/php/php8.5-fpm.sock;57 }58
59 location ~ \.php$ {60 try_files $uri =404;61 include fastcgi_params;62 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;63 fastcgi_pass unix:/run/php/php8.5-fpm.sock;64 }65}Check the config and reload:
shell
1sudo nginx -t && sudo systemctl reload nginxA few things that matter here:
- Order of regex locations. nginx uses the first regex
locationthat matches, so the uploads rule must come beforelocation ~ \.php$. Put it after, and the PHP block wins. try_files $uri =404in the PHP block stops requests like/wp-content/uploads/image.jpg/x.phpfrom being passed to PHP-FPM.- The
deny allfor.logalso coverswp-content/debug.log, which WordPress writes whenWP_DEBUG_LOGis on and which often contains paths and database errors. - The login limit counts only POST requests, so loading the login page is never blocked. A burst of 6 attempts goes through, then extra ones get
429until the limit refills at one attempt every 6 seconds.
⚠️ add_header inheritance. nginx drops all add_header lines from the server block in any location that has its own add_header. We checked it: a static files block with a single Cache-Control header lost every security header. On nginx 1.29.3 and newer, add add_header_inherit merge; to that location. On older versions, repeat the security headers inside it, or keep them in a snippet and include it in both places.
Apache
On Apache 2.4 the same rules go into the virtual host. Enable the headers module first with sudo a2enmod headers.
html
1<VirtualHost *:443>2 ServerName example.com3 DocumentRoot /var/www/example.com/public4
5 <Directory /var/www/example.com/public>6 Options -Indexes +SymLinksIfOwnerMatch7 AllowOverride All8 Require all granted9 </Directory>10
11 # No PHP execution in uploads12 <Directory /var/www/example.com/public/wp-content/uploads>13 <FilesMatch "\.(?i:php|phtml|phar)$">14 Require all denied15 </FilesMatch>16 </Directory>17
18 <Files xmlrpc.php>19 Require all denied20 </Files>21
22 <FilesMatch "^(readme\.html|license\.txt|wp-config\.php|wp-config-sample\.php)$">23 Require all denied24 </FilesMatch>25
26 <FilesMatch "\.(bak|old|orig|save|swp|sql|log|dist)$">27 Require all denied28 </FilesMatch>29
30 <LocationMatch "/\.(?!well-known/)">31 Require all denied32 </LocationMatch>33
34 Header always set Strict-Transport-Security "max-age=31536000"35 Header always set X-Content-Type-Options "nosniff"36 Header always set X-Frame-Options "SAMEORIGIN"37 Header always set Referrer-Policy "strict-origin-when-cross-origin"38 Header always set Permissions-Policy "camera=(), microphone=(), geolocation=()"39
40 # SSLEngine and certificate lines go here41</VirtualHost>Why .phtml and .phar are in the list: on Ubuntu, the Apache PHP module runs every file that matches .+\.ph(?:ar|p|tml)$, not just .php. Options -Indexes stops Apache from listing folders like wp-content/uploads/2026/11/, which have no index.php.
With read-only code, WordPress can't write its rewrite rules to .htaccess, so create that file once, owned by deploy. If you can only use .htaccess (shared hosting), put the uploads rule in wp-content/uploads/.htaccess:
html
1<FilesMatch "\.(?i:php|phtml|phar)$">2 Require all denied3</FilesMatch>We tested both variants: each returned 403 for .php, .phtml, .phar and .PHP in uploads.
Check the rules
Run these from any machine. Each line should print 403, except the first one:
shell
1curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' http://example.com/wp-admin/2curl -s -o /dev/null -w '%{http_code}\n' https://example.com/wp-content/uploads/test.php3curl -s -o /dev/null -w '%{http_code}\n' https://example.com/xmlrpc.php4curl -s -o /dev/null -w '%{http_code}\n' https://example.com/.git/config5curl -s -o /dev/null -w '%{http_code}\n' https://example.com/wp-config.php.bak6curl -s -o /dev/null -w '%{http_code}\n' https://example.com/readme.htmlThe first one should print 301 and the HTTPS address. Requests for files that don't exist are denied by the same rules, so you don't need to create test files. Then open the homepage, log in and save a post to make sure nothing legitimate is blocked.
6. Turn off XML-RPC if you don't need it
xmlrpc.php is an old remote API. Today it mostly serves brute-force attacks (one request can try hundreds of passwords with system.multicall) and pingback abuse. The block editor, the WordPress mobile apps and most integrations use the REST API instead.
The web server rules above already return 403 for xmlrpc.php, for GET and POST. That's better than a plugin, because PHP never runs. Before you block it, check whether you use Jetpack or an old desktop publishing tool: those still need XML-RPC. In that case leave it open and rely on the login limits and 2FA from the next section.
7. Protect the login
Rate limit login attempts. The nginx limit_req rule from section 5 does it before PHP runs. In our test, 15 quick wrong-password POSTs got 200 six times, then 429. On Apache, or for blocking whole IPs for longer, use your WAF (section 13) or Fail2ban.
Turn on two-factor authentication for every account that can publish or manage the site. The free Two Factor plugin, maintained by WordPress contributors, supports authenticator apps (TOTP), email codes and backup codes. Security keys and passkeys need its separate WebAuthn provider plugin. With option B, install it from WP-CLI:
shell
1wp plugin install two-factor --activateEach user then turns it on in their profile. We tested the login flow: with TOTP enabled, the right password alone didn't set the login cookie, and WordPress asked for the code. The plugin also slows down repeated wrong codes, so a few failed attempts lock the form for a while.
Don't make usernames easy. Don't use admin, and don't let the username double as the public author name. WordPress builds author URLs from the user_nicename field, which equals the username by default. Change it and the display name:
shell
1wp user update 1 --user_nicename=editorial-team --display_name="Editorial team"Review admins regularly. An extra administrator account is a classic sign of a compromise:
shell
1wp user list --role=administrator --fields=ID,user_login,user_emailTurn off application passwords unless an integration needs them. They let a user authenticate to the REST API and XML-RPC with a separate password, without the second factor. The plugin in the next section turns them off.
8. Close REST API user enumeration
Out of the box, anyone can list the users who have published posts:
shell
1curl -s https://example.com/wp-json/wp/v2/usersOn a fresh install that returned the admin's username in the slug field. The same data comes from /?rest_route=/wp/v2/users, from /?author=1 (it redirects to /author/<username>/) and from the users sitemap wp-sitemap-users-1.xml.
Blocking the URL in nginx isn't enough: the ?rest_route= form goes around it, and the block editor needs the users endpoint for logged-in authors. A small must-use plugin handles all of it inside WordPress. Save it as wp-content/mu-plugins/hardening.php, owned by deploy:
php
1<?php2/**3 * Plugin Name: Site hardening4 * Description: Hides user enumeration and XML-RPC leftovers from visitors.5 */6
7// Remove the users REST endpoints for visitors who are not logged in.8add_filter( 'rest_endpoints', function ( $endpoints ) {9 if ( ! is_user_logged_in() ) {10 unset( $endpoints['/wp/v2/users'], $endpoints['/wp/v2/users/(?P<id>[\d]+)'] );11 }12 return $endpoints;13} );14
15// Stop ?author=1 scans from redirecting to /author/<username>/.16add_action( 'template_redirect', function () {17 if ( isset( $_GET['author'] ) && ! is_user_logged_in() ) {18 wp_safe_redirect( home_url( '/' ), 301 );19 exit;20 }21}, 1 );22
23// Drop the users sitemap (wp-sitemap-users-1.xml).24add_filter( 'wp_sitemaps_add_provider', function ( $provider, $name ) {25 return 'users' === $name ? false : $provider;26}, 10, 2 );27
28// XML-RPC is blocked in the web server. This also drops the X-Pingback header.29add_filter( 'xmlrpc_enabled', '__return_false' );30add_filter( 'wp_headers', function ( $headers ) {31 unset( $headers['X-Pingback'] );32 return $headers;33} );34
35// Application passwords: turn them off unless an integration needs them.36add_filter( 'wp_is_application_passwords_available', '__return_false' );Must-use plugins load automatically and can't be turned off from the dashboard. After it was in place, both REST URLs returned rest_no_route (404), /?author=1 redirected to the homepage, and the users sitemap returned 404. Logged-in editors kept full access: the users endpoint with a valid REST nonce still answered 200, so the block editor works.
This hides usernames from casual scans. It doesn't replace strong passwords and 2FA, because a username was never meant to be a secret.
9. Send security headers
The headers in the nginx and Apache configs above do this:
Strict-Transport-Securitytells browsers to use only HTTPS for a year. Add it once HTTPS works for the whole domain.X-Content-Type-Options: nosniffstops browsers from guessing file types, so an uploaded text file with HTML inside isn't rendered as a page.X-Frame-Options: SAMEORIGINprevents other sites from loading yours in a frame (clickjacking).Referrer-Policystops full URLs, with query strings, from leaking to other sites.Permissions-Policyturns off browser features the site doesn't use.
always makes nginx send them on error pages too. A Content-Security-Policy is the strongest header, but the WordPress dashboard and most themes rely on inline scripts. Start with Content-Security-Policy-Report-Only, watch the reports, and enforce it only when the site is clean.
Check what the site sends:
shell
1curl -sI https://example.com/ | grep -iE 'strict|x-content|x-frame|referrer|permissions|server|x-powered'You should see the five headers, server: nginx without a version, and no X-Powered-By line.
10. Use HTTPS everywhere
The configs above redirect all HTTP traffic to HTTPS with a 301, FORCE_SSL_ADMIN keeps logins encrypted, and HSTS stops browsers from trying HTTP again. A free certificate from Let's Encrypt is enough for most sites, and it renews automatically: see our guide to installing Let's Encrypt on Ubuntu. Make sure the WordPress and site addresses in Settings, General start with https://.
11. Harden PHP
- Hide the PHP version. Set
expose_php = Offin thephp.inithat PHP-FPM loads (/etc/php/8.5/fpm/php.ini), thensudo systemctl reload php8.5-fpm. That removes theX-Powered-Byheader.server_tokens offdoes the same for nginx. - Disable dangerous functions such as
exec,shell_execandsystemwithdisable_functions. It's a speed bump for web shells, not a sandbox, and it's easy to edit the wrongphp.ini. Our guide on disabling dangerous PHP functions shows the right file, a safe list and how to check it. - One PHP-FPM pool per site. If a server hosts several sites, give each one its own pool and Linux user. Then a hacked site can't read another site's
wp-config.php. The same guide shows the pool config. - Keep PHP on a supported version. Use a PHP branch that still gets security fixes and that your plugins support.
12. Take backups you can restore
A backup you've never restored is a hope, not a backup. Back up two things: the database and wp-content/uploads. Core, plugins and themes can be downloaded again from the official directory or your repository.
shell
1wp db export --single-transaction /srv/backups/db-$(date +%F).sql2tar -czf /srv/backups/uploads-$(date +%F).tar.gz -C /var/www/example.com/public/wp-content uploads--single-transaction matters with a least-privilege user. Without it, the dump stops with Access denied ... when using LOCK TABLES, because the user from section 4 has no LOCK TABLES right. With it, the dump runs as one consistent InnoDB snapshot and needs no locks.
Store backups outside the web root (never in public), copy them off the server, and keep several days. Then actually restore one, at least on a staging copy:
shell
1wp db import /srv/backups/db-2026-11-04.sql13. Monitor the site and put a WAF in front of it
Check file integrity. WP-CLI compares core and plugin files with the official checksums published for each release:
shell
1wp core verify-checksums2wp plugin verify-checksums --allWhen we appended a line to a core file and dropped an extra PHP file into wp-includes, verify-checksums failed and named both. Run it daily from cron and alert on failure. Premium plugins and custom code have no official checksums, so keep those in Git and compare against it.
Look for PHP files in uploads. There should be none:
shell
1find /var/www/example.com/public/wp-content/uploads -type f -iname '*.ph*'Scan for malware on the server, not just inside WordPress. Our guide to Linux Malware Detect covers setup and scheduled scans.
Put a WAF in front of the site. Open only ports 80, 443 and SSH in the firewall. Then filter the traffic that does reach the site: a managed WAF such as Cloudflare blocks known exploit patterns, bad bots and floods before they reach your server, and hides its address. On your own server, ModSecurity with the OWASP Core Rule Set does a similar job. If you use a proxy, let the web server accept traffic only from the proxy's IP ranges, otherwise attackers simply go around it.
Read the logs. Repeated 429 and 403 responses from one address, POSTs to files that shouldn't exist, and new admin users are all worth an alert.
Wrapping up
None of these steps is hard on its own. The value is in doing all of them and checking each one, because attackers only need the one you skipped. Start with updates, read-only code and the uploads rule: those three stop most real-world attacks we see. Then add 2FA, the web server rules and backups you've restored at least once.
If you'd rather have someone else harden and watch your WordPress servers, our team does it as part of our cloud security and compliance services.
