Preloader Close

The Ultimate WordPress Security Guide (2027)

Creative Website Design & Development

The Ultimate WordPress Security Guide (2027)













To secure a WordPress site in 2027, enforce HTTPS with HSTS headers, keep all core files and plugins updated, use two-factor authentication on every admin account, deploy a web application firewall and maintain automated off-site backups. These five layers block over 95% of common WordPress attacks before they reach your data.

This WordPress security guide covers every layer of defence your site needs. Whether you run a personal blog or an ecommerce store processing thousands of transactions, the techniques below are practical, tested and ranked by impact. Pair this guide with our WordPress security checklist for a step-by-step action plan.

Hosting and Server Security

Your hosting environment is the foundation of your WordPress security posture. A poorly configured server undermines every plugin and firewall you install on top of it.

Choose a Security-Focused Host

Not all WordPress hosts are equal. Look for providers that offer server-level firewalls, automatic malware scanning, isolated account environments (no shared PHP workers across accounts) and proactive kernel patching. Managed WordPress hosts like Kinsta, WP Engine and Cloudways handle server-level hardening so you can focus on application security.

Key features to verify before signing up:

  • PHP 8.2+ support with automatic minor version updates
  • Server-side malware scanning (not just plugin-level)
  • Network-level DDoS protection
  • Isolated container or VM-based environments
  • Automatic daily backups with one-click restore
  • SSH and SFTP access (never plain FTP)

Configure PHP for Security

PHP misconfigurations are responsible for a large percentage of WordPress exploits. Harden your php.ini settings to reduce your attack surface:

; Disable dangerous functions
disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_multi_exec,parse_ini_file,show_source
; Hide PHP version from response headers
expose_php = Off
; Limit file uploads
file_uploads = On
upload_max_filesize = 10M
max_file_uploads = 5
; Session security
session.cookie_httponly = 1
session.cookie_secure = 1
session.use_strict_mode = 1
; Prevent remote file inclusion
allow_url_fopen = Off
allow_url_include = Off

If your host uses a managed panel, request these changes through support. Most managed WordPress hosts already enforce them by default.

Enforce SFTP and SSH Access Only

Plain FTP transmits credentials in cleartext. One packet sniffer on a shared network gives an attacker your server password. SFTP encrypts the entire session. Disable FTP entirely in your server configuration and use SSH key-based authentication for command-line access.

SSL/TLS and HTTPS Configuration

HTTPS is not optional. Google penalizes unencrypted sites in search rankings and browsers display a “Not Secure” warning that kills visitor trust. But simply installing an SSL certificate is not enough.

Install and Verify Your SSL Certificate

Most hosts offer free SSL through Let’s Encrypt with automatic renewal. After installation, verify your setup:

  • Visit your site at https://yourdomain.com and confirm the padlock icon appears
  • Run an SSL test at SSL Labs and aim for an A+ grade
  • Check that all internal resources (images, scripts, stylesheets) load over HTTPS to avoid mixed content warnings

Force HTTPS With Redirects and HSTS

A 301 redirect from HTTP to HTTPS is the bare minimum. Add HTTP Strict Transport Security (HSTS) to tell browsers to never attempt an insecure connection:

# Add to .htaccess (Apache) or nginx config
# Apache
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
# Nginx
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

Update your WordPress settings (Settings > General) so both the WordPress Address and Site Address use https://. Then add these lines to wp-config.php:

define('FORCE_SSL_ADMIN', true);
define('FORCE_SSL_LOGIN', true);

Login and Authentication Hardening

The WordPress login page is the most targeted endpoint on any installation. Brute force bots hammer /wp-login.php thousands of times per day. Hardening authentication stops the majority of automated attacks.

Enforce Strong Passwords and Two-Factor Authentication

Every account with dashboard access needs a unique password of at least 16 characters generated by a password manager. Pair this with two-factor authentication (2FA) using a time-based one-time password (TOTP) app like Authy or Google Authenticator. Avoid SMS-based 2FA as it is vulnerable to SIM-swapping attacks.

Recommended 2FA plugins:

  • WP 2FA – lightweight, supports TOTP and backup codes
  • Wordfence Login Security – standalone 2FA module from the Wordfence team
  • miniOrange – supports TOTP, push notifications and hardware keys

Limit Login Attempts

WordPress allows unlimited login attempts by default. Install a rate-limiting plugin or configure your WAF to lock out an IP address after five failed attempts for at least 30 minutes. Progressive lockouts (longer bans for repeat offenders) are even more effective.

Change the Login URL

Moving /wp-login.php to a custom URL stops automated bots that target the default path. Plugins like WPS Hide Login handle this with a single setting change. This is security through obscurity and should never be your only defence, but it dramatically reduces bot traffic and server load.

Disable the Default “admin” Username

If an account named “admin” exists on your site, attackers have 50% of the credentials they need. Create a new administrator account with a unique username, transfer content ownership and delete the “admin” account entirely.

Block xmlrpc.php

The XML-RPC interface allows brute force amplification attacks. A single request can test hundreds of passwords simultaneously using the system.multicall method. Unless you use a mobile app or service that requires XML-RPC, block it at the server level:

# Apache .htaccess
<Files xmlrpc.php>
  Require all denied
</Files>
# Nginx
location = /xmlrpc.php {
  deny all;
  return 403;
}

Plugin and Theme Security

Plugins and themes account for over 90% of known WordPress vulnerabilities. Every piece of third-party code you install expands your attack surface. A disciplined approach to plugin management is essential for any serious WordPress security guide.

Audit Before You Install

Before adding any plugin or theme, verify the following:

  • Last updated – anything not updated within the past six months is a risk
  • Active installs – larger user bases mean faster vulnerability discovery and patching
  • Support forum activity – check if the developer responds to security reports
  • Known vulnerabilities – search the WPScan Vulnerability Database and Patchstack before installing
  • Code quality – for premium plugins, request access to the codebase or read independent security audits

Maintain a Lean Plugin Stack

Every active plugin is a potential entry point. Deactivated plugins are equally dangerous because the code still exists on your server. Delete anything you are not using. Aim for under 20 active plugins on most sites. If a feature can be achieved with a code snippet in your theme’s functions.php file, prefer that over adding another plugin.

Use Themes From Trusted Sources Only

Nulled (pirated) themes are the fastest way to get hacked. They almost always contain backdoors, hidden admin accounts or cryptocurrency miners. Download themes only from the official WordPress.org repository, established theme shops (like developer marketplaces from Flavor Theme or Flavor Theme) or developers whose code you can personally audit.

Enable Automatic Updates for Security Patches

WordPress supports auto-updates for plugins and themes. Enable them for all plugins at minimum. If you are concerned about breaking changes, use a staging environment to test updates before they reach production. Many managed hosts offer this workflow built into their dashboards.

File Permissions and Filesystem Hardening

Incorrect file permissions let attackers modify core files, inject malware or escalate privileges. Locking down the filesystem is a foundational step in hardening your WordPress installation.

Set Correct File and Directory Permissions

Apply these permission values across your WordPress installation:

PathPermissionReason
Directories755Owner can read/write/execute; group and others can read/execute
Files644Owner can read/write; group and others can read only
wp-config.php400 or 440Owner read only; prevents web server from writing to it
.htaccess444Read only for everyone; prevents unauthorized redirect injection

Apply these permissions via SSH:

# Set directory permissions
find /path/to/wordpress -type d -exec chmod 755 {} ;
# Set file permissions
find /path/to/wordpress -type f -exec chmod 644 {} ;
# Lock down wp-config.php
chmod 400 /path/to/wordpress/wp-config.php

Disable PHP Execution in Uploads

The wp-content/uploads/ directory should never execute PHP files. Attackers who upload a malicious PHP shell through a vulnerable plugin can use it to take full control of your server. Block execution with an .htaccess file inside the uploads directory:

# wp-content/uploads/.htaccess
<Files "*.php">
  Require all denied
</Files>

On Nginx, add this to your server block:

location ~* /wp-content/uploads/.*.php$ {
  deny all;
}

Protect wp-config.php

This file contains your database credentials, authentication keys and salt values. Move it one directory above your web root if your hosting environment supports it. WordPress automatically checks the parent directory for wp-config.php. Additionally, block web access entirely:

# .htaccess
<Files wp-config.php>
  Require all denied
</Files>

Disable File Editing in the Dashboard

The built-in Theme Editor and Plugin Editor let anyone with admin access modify PHP files directly from the browser. If an attacker compromises an admin account, this feature gives them instant code execution. Disable it in wp-config.php:

define('DISALLOW_FILE_EDIT', true);

For tighter control, also prevent plugin and theme installations through the dashboard:

define('DISALLOW_FILE_MODS', true);

Database Security

Your WordPress database stores everything: posts, user credentials, site settings and plugin data. A compromised database means total site takeover.

Change the Default Table Prefix

WordPress uses wp_ as the default table prefix. Automated SQL injection attacks target this prefix specifically. Changing it to something unique (like qm7x_) breaks those automated queries. Set this during installation. Changing it on a live site requires updating the prefix in wp-config.php and renaming every table in the database, so plan carefully.

Use a Dedicated Database User With Minimal Privileges

Never connect WordPress to your database using the root account. Create a dedicated database user with only the permissions WordPress needs:

-- Create a restricted database user
CREATE USER 'wp_site_user'@'localhost' IDENTIFIED BY 'strong_random_password_here';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER
  ON wordpress_db.*
  TO 'wp_site_user'@'localhost';
FLUSH PRIVILEGES;

Avoid granting FILE, PROCESS, SUPER or GRANT privileges. WordPress never needs them.

Regenerate Authentication Keys and Salts

WordPress uses secret keys and salts to encrypt cookies and session tokens. If an attacker obtains your wp-config.php file, they can forge authentication cookies. Regenerate these values periodically using the WordPress secret key generator and paste the output into wp-config.php. This immediately invalidates all existing sessions and forces every user to log in again.

Restrict Database Access to localhost

Your database should only accept connections from your web server. Bind MySQL/MariaDB to 127.0.0.1 in your database configuration and block port 3306 at the firewall level. Remote database connections should only exist if your application architecture requires a separate database server, and even then, restrict access to the web server’s IP only.

Web Application Firewall (WAF) Configuration

A WAF inspects incoming HTTP traffic and blocks malicious requests before they reach WordPress. It is the single most effective layer of defence against SQL injection, cross-site scripting (XSS) and zero-day exploits. If you implement nothing else from this WordPress security guide, deploy a WAF.

Cloud-Based vs. Plugin-Based WAFs

You have two main options:

  • Cloud-based WAFs (Cloudflare, Sucuri, AWS WAF) sit between your visitors and your server. They filter traffic at the network edge and absorb DDoS attacks before they hit your infrastructure. This is the preferred option for most sites.
  • Plugin-based WAFs (Wordfence, NinjaFirewall) run on your server. They catch application-layer attacks but consume your server’s CPU and memory. They cannot mitigate volumetric DDoS attacks.

For maximum protection, stack both: a cloud WAF at the edge plus a plugin-level WAF for application-layer rules.

Essential WAF Rules for WordPress

Configure your WAF to block these common attack patterns:

  • SQL injection attempts in query strings and POST data
  • Cross-site scripting (XSS) payloads in form fields and URL parameters
  • Path traversal attempts targeting ../ sequences
  • PHP file upload attempts to non-upload directories
  • Requests to xmlrpc.php and wp-trackback.php
  • User-agent strings matching known vulnerability scanners (WPScan, Nikto, SQLMap)
  • Rate limiting on /wp-login.php and /wp-admin/admin-ajax.php

Integrate Your WAF With a CDN

Cloud WAFs like Cloudflare double as content delivery networks. This gives you both security and performance: static assets are served from edge nodes while malicious requests are filtered before they reach your origin server. Ensure your origin server IP remains hidden by routing all traffic through the CDN and blocking direct IP access.

Security Headers

HTTP security headers instruct browsers to enforce security policies that prevent common attacks. Most WordPress sites ship with zero security headers configured. Adding them takes minutes and blocks entire categories of exploits.

Essential Headers for Every WordPress Site

Add these headers through your .htaccess file, Nginx config or a plugin like HTTP Headers:

# Content Security Policy - restrict resource loading
Header set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://www.googletagmanager.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://www.google-analytics.com"
# Prevent MIME type sniffing
Header set X-Content-Type-Options "nosniff"
# Prevent clickjacking
Header set X-Frame-Options "SAMEORIGIN"
# Control referrer information
Header set Referrer-Policy "strict-origin-when-cross-origin"
# Restrict browser features
Header set Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=()"
# Force HTTPS (set after confirming HTTPS works correctly)
Header set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"

Content Security Policy Deep Dive

CSP is the most powerful security header and the most complex to configure. A strict CSP prevents XSS attacks by controlling which scripts, styles and resources the browser is allowed to load. Start with a report-only policy to identify violations before enforcing:

Header set Content-Security-Policy-Report-Only "default-src 'self'; report-uri /csp-report-endpoint"

Monitor the reports for a week, whitelist legitimate sources and then switch to enforcement mode. WordPress sites that use Google Analytics, reCAPTCHA or third-party ad scripts will need specific exceptions for those domains.

Test Your Headers

After configuration, verify your headers using SecurityHeaders.com. Aim for an A+ grade. Check that no headers conflict with your theme or plugins. A misconfigured CSP will break your site’s frontend, so always test on staging first.

Backup Strategy

Backups are your last line of defence. If every other security measure fails, a clean backup lets you restore your site within minutes. A backup strategy that only exists on the same server as your site is not a strategy at all.

The 3-2-1 Backup Rule

Follow the 3-2-1 principle:

  • 3 copies of your data (production site plus two backups)
  • 2 different storage types (local server snapshot plus cloud storage)
  • 1 off-site copy (Amazon S3, Google Cloud Storage or a geographically separate server)

What to Back Up

A complete WordPress backup includes:

  • The entire wp-content directory (themes, plugins, uploads and custom files)
  • The MySQL/MariaDB database (all tables)
  • wp-config.php and any custom server configuration files
  • .htaccess or Nginx configuration files

Automate and Test Regularly

Use plugins like UpdraftPlus, BlogVault or BackupBuddy to automate daily backups. High-traffic ecommerce sites should use real-time incremental backups that capture every database change as it happens. Store backups in at least two off-site locations.

The backup that matters most is the one you have tested. Restore your backup to a staging environment at least once per month. Verify that the site loads correctly, all data is intact and login credentials work. An untested backup is no better than no backup.

Security Monitoring and Threat Detection

Prevention is half the battle. The other half is knowing when something goes wrong. Active monitoring catches breaches early and limits the damage.

File Integrity Monitoring

File integrity monitoring (FIM) tracks changes to your WordPress core files, theme files and plugin files. When an attacker modifies a file to inject malware, FIM alerts you immediately. Wordfence, Sucuri and iThemes Security all include FIM features. For server-level monitoring, tools like OSSEC or Tripwire provide deeper coverage.

Uptime and Availability Monitoring

A sudden site outage can indicate a DDoS attack, a server compromise or a defacement. Use external monitoring services (UptimeRobot, Pingdom or Better Uptime) to check your site every 60 seconds. Configure alerts to notify you via email, SMS and Slack the moment your site goes down.

Login Activity Logging

Track every login attempt: successful and failed. Log the username, IP address, timestamp and user agent. Plugins like WP Activity Log capture this data and flag suspicious patterns like logins from new geographic locations or multiple failed attempts from the same IP range.

Security Scanning Schedule

Run automated security scans on a consistent schedule:

  • Daily: Malware scan (Wordfence or Sucuri)
  • Weekly: Full file integrity check against WordPress.org checksums
  • Monthly: Manual review of user accounts, plugin audit and permissions check
  • Quarterly: Full security audit including penetration testing on staging

Review your monitoring dashboards weekly. Automated alerts catch the obvious threats. Manual review catches the subtle ones that automated tools miss.

WordPress REST API Security

The REST API ships enabled by default and exposes sensitive data to unauthenticated requests. Disabling it entirely breaks the block editor and many plugins. The correct approach is to restrict access to specific endpoints. Our complete guide to securing the WordPress REST API covers this topic in depth.

Block User Enumeration

The /wp-json/wp/v2/users endpoint reveals usernames and user IDs to anyone who requests them. Attackers use this data to target brute force attacks. Restrict it to authenticated users only:

// Add to functions.php or a custom security plugin
add_filter('rest_endpoints', function($endpoints) {
    if (!is_user_logged_in()) {
        if (isset($endpoints['/wp/v2/users'])) {
            unset($endpoints['/wp/v2/users']);
        }
        if (isset($endpoints['/wp/v2/users/(?P<id>[d]+)'])) {
            unset($endpoints['/wp/v2/users/(?P<id>[d]+)']);
        }
    }
    return $endpoints;
});

Enforce Authentication on Custom Endpoints

If you or your developers create custom REST API routes, always include a permission_callback that validates the user’s capabilities. Routes without permission callbacks are open to the public by default. This is one of the most common security mistakes in WordPress plugin development.

Incident Response Plan

Every site will face a security incident eventually. The difference between a minor disruption and a catastrophic breach is how quickly and effectively you respond. Build your incident response plan before you need it.

Step 1: Contain the Threat

The moment you confirm a breach:

  • Put the site into maintenance mode to prevent further damage
  • Change all passwords immediately: WordPress admin, database, SFTP, hosting panel and any connected third-party services
  • Revoke all active sessions by regenerating authentication keys and salts in wp-config.php
  • Block the attacker’s IP addresses at the firewall level

Step 2: Assess the Damage

Determine what was compromised:

  • Run a full malware scan with multiple tools (Wordfence plus Sucuri for cross-verification)
  • Compare core files against WordPress.org checksums using wp core verify-checksums via WP-CLI
  • Check the database for unauthorized admin accounts or modified content
  • Review server access logs for the attacker’s entry point and lateral movement
  • Identify whether customer data (PII, payment information) was accessed or exfiltrated

Step 3: Clean and Restore

If the infection is limited to a few files, manually remove the malicious code and verify the fix. For widespread compromise, restore from the most recent clean backup and then apply all security updates. Replace all plugins and themes with fresh copies from their original sources. Never trust a compromised file even after “cleaning” it.

Step 4: Harden and Document

After restoring service:

  • Implement the specific countermeasures that would have prevented the breach
  • Document the incident timeline, root cause and remediation steps
  • Notify affected users if personal data was compromised (this may be legally required under PIPEDA, GDPR or your local data protection laws)
  • Schedule a post-incident review to update your security policies

A documented incident response plan turns chaos into process. Keep a printed copy accessible in case your digital systems are compromised. For professional support building or auditing your WordPress security posture, explore our web development services.

Advanced Hardening Techniques

The measures above cover the core layers of WordPress security. The techniques below add additional protection for high-value targets or sites that handle sensitive data.

Implement Content Security Policy Nonces

Instead of allowing 'unsafe-inline' in your CSP (which weakens it significantly), generate a unique nonce for each page load and attach it to your inline scripts. WordPress 6.x supports this through the wp_get_script_tag() and wp_add_inline_script() functions. This approach blocks injected scripts while allowing your legitimate inline code to execute.

Use Security Keys With Hardware Tokens

TOTP-based 2FA is good. Hardware security keys (YubiKey, Google Titan) using the WebAuthn/FIDO2 standard are better. They are immune to phishing, cannot be intercepted remotely and do not rely on a phone battery. The WP WebAuthn plugin brings hardware key support to WordPress.

Deploy a Server-Level Intrusion Detection System

Tools like Fail2Ban, OSSEC and CrowdSec monitor system logs and automatically block IP addresses that exhibit malicious behaviour. Configure Fail2Ban to watch your WordPress access logs for patterns like repeated 404 errors on sensitive paths (/wp-admin, /wp-login.php) or scanning tool user agents.

Isolate WordPress With Containerization

Running WordPress inside a Docker container or a sandboxed environment (like gVisor) limits the blast radius of a compromise. Even if an attacker gains code execution inside the container, they cannot access the host filesystem or other applications on the server. This architecture is increasingly common in enterprise WordPress deployments.

Schedule Regular Penetration Tests

Automated scanners catch known vulnerabilities. Penetration testing by a skilled practitioner finds the logic flaws, misconfigurations and chained attack paths that scanners miss. Schedule a penetration test at least annually, or after any major site change. Need a professional assessment? Start with our free security audit.

WordPress Security FAQ

How often should I update WordPress core, themes and plugins?

Apply security patches within 24 hours of release. Schedule routine updates weekly. Enable automatic minor core updates and use a staging environment to test major releases before pushing to production. Set a calendar reminder to check for updates every Monday morning so nothing slips through the cracks.

Is a free security plugin enough to protect my WordPress site?

Free plugins like Wordfence or Sucuri cover basic firewall rules and malware scanning. However, they lack real-time threat intelligence feeds, priority patching and dedicated incident response support that premium tiers provide. For business-critical sites, paid protection is worth the investment. Pair a premium plugin with a cloud-based WAF for layered defence.

What file permissions should I set on a WordPress installation?

Set directories to 755, files to 644 and wp-config.php to 400 or 440. The wp-content/uploads directory should be 755 but never allow PHP execution inside it. Incorrect permissions are one of the most common misconfigurations we find during security audits.

Do I really need a Web Application Firewall for WordPress?

Yes. A WAF blocks SQL injection, cross-site scripting and zero-day exploit attempts before they reach your application layer. Cloud-based WAFs like Cloudflare or Sucuri also absorb DDoS traffic, reducing server load and preventing downtime. It is the highest-impact single security measure you can deploy.

How do I know if my WordPress site has been hacked?

Common indicators include unexpected admin accounts, modified core files, unfamiliar JavaScript injections, sudden traffic spikes from suspicious regions, Google Search Console security warnings and your site redirecting to spam domains. File integrity monitoring and daily malware scans catch most compromises early. Check our WordPress security checklist for a complete list of warning signs.

Should I disable the WordPress REST API entirely?

Do not disable it entirely because the block editor and many plugins depend on it. Instead, restrict unauthenticated access to sensitive endpoints like /wp-json/wp/v2/users and enforce authentication on custom routes. Our guide to securing the WordPress REST API walks through the process step by step.

How often should I back up my WordPress site?

Back up daily at minimum. High-traffic or ecommerce sites should use real-time incremental backups that capture every database change. Store copies in at least two off-site locations (cloud storage and a separate server). Test your restoration process monthly to confirm backups are functional and complete.

What security headers should every WordPress site use?

At minimum, implement Content-Security-Policy, X-Content-Type-Options (nosniff), X-Frame-Options (SAMEORIGIN), Referrer-Policy (strict-origin-when-cross-origin), Permissions-Policy and Strict-Transport-Security (HSTS). These headers prevent clickjacking, MIME sniffing, data leakage and protocol downgrade attacks. Test your configuration at SecurityHeaders.com after deployment.

Related: what technical SEO is

Related: marketing strategy guide and web development FAQ

Need help with this?

Quake Media helps businesses across Vancouver and Canada with SEO, PPC and custom web development. Get a free audit and see where your site stands.

★★★★★ 5.0 on Google Reviews

The Ultimate WordPress Security Guide (2027)

Free Website Audit

Find out what is holding your site back. We identify SEO, security and performance issues for free.

Request Audit 604-901-7668

Request a free quote

Let us know what you are looking for and we will get right back to you!