How to Secure an Existing WordPress Site in Six Easy Steps

WordPress is the undisputed king of content management systems, powering a staggering 40% of all websites on the internet. With over 60 million installations, it‘s the go-to platform for businesses, bloggers, and online stores around the world.

However, this widespread popularity has also made WordPress a prime target for hackers and cybercriminals. According to a 2020 report from Sucuri, 94% of all websites cleaned for malware infections were built on WordPress. The vast attack surface presented by millions of WordPress sites is simply too tempting for malicious actors to ignore.

As a full-stack developer, it‘s crucial to prioritize security when working with WordPress. A single successful breach can have devastating consequences, from data theft and SEO penalties to complete site takeovers. Fortunately, by following a collection of security best practices and hardening techniques, you can fortify your WordPress sites against the most common threats.

In this comprehensive guide, I‘ll walk you through six essential steps to secure an existing WordPress installation. These are battle-tested measures I‘ve employed across hundreds of client sites as a professional WordPress developer. They‘re based on the latest data from security researchers and real-world breach reports.

Whether you‘re a seasoned WordPress pro or just getting started with the platform, these steps will help you lock down your sites and protect your users. Let‘s dive in!

Step 1: Update WordPress to the Latest Version

One of the most fundamental aspects of WordPress security is keeping the core software up to date. Each new version of WordPress includes fixes for bugs, performance improvements, and most importantly, patches for known vulnerabilities.

However, a shocking number of WordPress sites are running outdated versions. A 2020 scan by WPScans.com found that over 70% of WordPress installations had unpatched vulnerabilities. These sites are low-hanging fruit for attackers, who actively seek out unpatched targets.

Failing to update WordPress core is like leaving your front door unlocked. It‘s an open invitation for hackers to exploit well-known security holes. As a developer, it‘s your responsibility to ensure all your WordPress sites are running the latest version.

Before updating, be sure to backup the entire WordPress filesystem and database. Although updates are generally safe, it‘s always possible for something to go wrong. A full backup gives you a failsafe to restore from if needed.

I recommend configuring automatic updates in WordPress to apply security patches as soon as they‘re released. You can enable auto-updates by adding the following code to your wp-config.php file:

define( ‘WP_AUTO_UPDATE_CORE‘, true );

With automatic updates, WordPress will install minor versions (e.g. 5.7.1 to 5.7.2) without any intervention. For major version updates (e.g. 5.7 to 5.8), you‘ll still need to manually trigger the update from the WordPress dashboard.

By staying on top of WordPress core updates, you eliminate a huge percentage of potential attack vectors. It‘s the simplest and most impactful security step you can take.

Step 2: Audit and Update All Plugins

While the WordPress core is the foundation, most of the functionality in a typical WordPress site comes from plugins. The official WordPress.org plugin directory hosts nearly 60,000 free plugins, and there are thousands more premium options sold on marketplaces like CodeCanyon.

However, this vibrant plugin ecosystem is also a major source of vulnerabilities. In a survey of over 400 WordPress site owners, security firm Wordfence found that 60% of respondents had experienced a security issue related to a plugin.

Plugins are written by thousands of independent developers of varying skill levels. Many of these developers don‘t follow proper security practices or fail to maintain their plugins over time. As a result, plugin vulnerabilities are a constant concern in the WordPress world.

To mitigate plugin-related threats, I recommend conducting a full audit of all active plugins on your WordPress sites. Use a spreadsheet or database to inventory every plugin, including its version number, last update date, and purpose.

Once you have a complete list, ruthlessly eliminate any plugins that aren‘t absolutely necessary. Every active plugin is a potential attack surface, so it‘s best to keep the number to a minimum. If a plugin hasn‘t been used in the past 6 months, chances are you don‘t really need it.

After trimming the fat, update all remaining plugins to their latest versions. Check the changelogs to verify that the updates include security enhancements. If you find any plugins that haven‘t been updated in over a year, consider replacing them with an actively maintained alternative.

Many major security incidents have been traced back to outdated or abandoned plugins. In 2020, an unpatched vulnerability in a popular WordPress plugin allowed attackers to hijack over 100,000 sites. By keeping your plugin stack lean and up-to-date, you can avoid falling victim to similar exploits.

Step 3: Enforce Strong Authentication

Even if your WordPress site is free of software vulnerabilities, it can still be compromised by stolen login credentials. Brute force attacks, where hackers use automated tools to guess passwords, are incredibly common in the WordPress world.

To protect your site from unauthorized logins, it‘s crucial to enforce strong authentication policies. Start by reviewing all of your WordPress user accounts and removing any that are inactive or unnecessary. The principle of least privilege dictates that each user should have the minimum permissions needed to perform their role.

WordPress has six built-in user roles, ranging from Super Admin to Subscriber. As a general rule, you should have no more than 1-2 Super Admin accounts. These are for trusted developers who need complete control over the site.

The Administrator role is appropriate for users who need to manage content and plugins but don‘t require low-level access. Editors can publish and manage posts from all users, while Authors and Contributors are limited to their own content. Subscribers can only access protected content areas.

Once you‘ve reviewed and adjusted user roles, it‘s time to strengthen login security with two-factor authentication (2FA). 2FA requires users to provide a second piece of evidence in addition to their password, such as a code from a mobile app.

There are several excellent 2FA plugins for WordPress, but I recommend Google Authenticator for its simplicity and wide device support. It generates time-based one-time passwords (TOTP) that users must enter along with their regular credentials.

Here‘s an example of how to integrate Google Authenticator with the popular WP-Members plugin:

function my_2fa_auth($user)
{
    $ga = new PHPGangsta_GoogleAuthenticator();
    $secret = get_user_meta($user->ID, ‘ga_secret‘, true);

    if (isset($_POST[‘code‘])) {
        $code = $_POST[‘code‘];
        $checkResult = $ga->verifyCode($secret, $code, 2);

        if (!$checkResult) {
            return new WP_Error(‘invalid_code‘, ‘Invalid verification code.‘);
        }
    } else {
        return new WP_Error(‘no_code‘, ‘Please enter the verification code.‘);
    }

    return $user;
}
add_filter(‘authenticate‘, ‘my_2fa_auth‘, 30, 1);

With 2FA enabled, an attacker would need both a user‘s password and physical access to their mobile device to log in. It‘s an incredibly effective way to stop brute force attacks and credential stuffing.

By locking down user permissions and implementing 2FA, you can greatly reduce the risk of unauthorized access to your WordPress dashboard. It‘s an essential layer in a defense-in-depth security strategy.

Step 4: Harden wp-config.php and .htaccess

WordPress configuration files such as wp-config.php and .htaccess control low-level behaviours and grant access to sensitive directories. As such, they‘re prime targets for attackers seeking to escalate their access or plant malicious payloads.

To harden your WordPress installation, it‘s crucial to lock down these files and prevent unauthorized modifications. Here are a few key steps I recommend:

  1. Move wp-config.php up one level from the web root directory. This makes it harder for attackers to access the file via the web server.

  2. Set strict file permissions on wp-config.php and .htaccess. Use 440 (read-only for owner) or 400 (read-only for all) to prevent accidental or malicious changes.

  3. Disable PHP execution in untrusted directories such as /wp-content/uploads/. Add the following code block to the .htaccess file in the target directory:

<Files *.php>
    deny from all
</Files>
  1. Restrict access to sensitive files like wp-config.php, install.php, and xmlrpc.php. Use .htaccess rules to whitelist specific IP addresses or block access entirely. For example:
<Files wp-config.php>
    order allow,deny
    deny from all
</Files>

<Files xmlrpc.php>
    order allow,deny
    allow from xxx.xxx.xxx.xxx
    deny from all
</Files>
  1. Disable directory indexing and browsing. Add the following line to your .htaccess file in the web root:
Options -Indexes

By implementing these hardening measures, you can significantly reduce the attack surface of your WordPress site. Attackers will have a much harder time accessing sensitive files or using them to gain unauthorized access.

Step 5: Limit Information Disclosure

By default, WordPress discloses a lot of information about your site‘s configuration and underlying technology stack. While this information is helpful for developers, it can also be used by attackers to identify potential vulnerabilities.

To limit information disclosure, I recommend the following steps:

  1. Disable debug mode and error reporting. In the wp-config.php file, make sure the following lines are present:
define(‘WP_DEBUG‘, false);
@ini_set(‘display_errors‘, 0);
  1. Remove the WordPress version number from the generator meta tag. Add the following code to your theme‘s functions.php file:
remove_action(‘wp_head‘, ‘wp_generator‘);
  1. Disable the XML-RPC API if not needed. XML-RPC is a legacy feature that‘s often targeted by brute force attacks. If you don‘t require it for features like remote publishing, disable it entirely by adding the following line to your wp-config.php file:
define(‘XMLRPC_ENABLED‘, false);
  1. Hide the login error messages. By default, WordPress login errors specify whether an entered username is valid or not. This can be used by attackers to enumerate valid usernames. To hide these messages, add the following code to your theme‘s functions.php file:
function wrong_login() {
    return ‘Wrong username or password.‘;
}
add_filter(‘login_errors‘, ‘wrong_login‘);
  1. Disable author pages and user enumeration. WordPress author pages can be used to glean valid usernames. To disable these pages and prevent user enumeration, add the following code to your theme‘s functions.php file:
function disable_author_page() {
    global $wp_query;

    if ( is_author() ) {
        $wp_query->set_404();
        status_header(404);
    }
}
add_action(‘template_redirect‘, ‘disable_author_page‘);

add_filter(‘rest_endpoints‘, function($endpoints){
    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;
});

By limiting the amount of information your WordPress site discloses, you make it harder for attackers to find and exploit vulnerabilities. It‘s a key aspect of a proactive security strategy.

Step 6: Implement a Web Application Firewall (WAF)

Even with all of the above hardening measures in place, there‘s always a chance that a new vulnerability or attack technique could slip through the cracks. That‘s where a web application firewall (WAF) comes in.

A WAF acts as a gatekeeper for your WordPress site, analyzing incoming traffic and blocking requests that match known attack patterns. It‘s an essential last line of defense against a wide range of threats, from SQL injection and cross-site scripting (XSS) to malicious bots and DDoS attacks.

There are many WAF solutions available for WordPress, but I recommend Sucuri or Wordfence for their comprehensive rulesets and user-friendly interfaces. Both offer free and paid versions, with features like malware scanning, brute force protection, and log monitoring.

Here‘s an example of how to integrate the Sucuri WAF with WordPress using the official plugin:

  1. Install and activate the Sucuri Security plugin from the WordPress.org repository.
  2. Navigate to the Sucuri Security menu in the WordPress dashboard and click on "Web Application Firewall".
  3. Click on "Optimize .htaccess Security" to add the necessary WAF rules to your .htaccess file.
  4. Configure the WAF settings according to your needs, such as the level of protection, whitelisted IPs, and log retention.
  5. Monitor the WAF logs regularly for any suspicious activity or blocked requests.

By implementing a WAF, you add a powerful layer of active protection to your WordPress site. It can stop attacks before they ever reach your server, saving you time and headaches in the long run.

Conclusion

WordPress security is an ongoing process that requires constant vigilance and proactive measures. As a full-stack developer, it‘s your responsibility to stay on top of the latest threats and implement best practices to keep your sites safe.

In this guide, we‘ve covered six essential steps to secure an existing WordPress installation:

  1. Update WordPress core to the latest version.
  2. Audit and update all plugins.
  3. Enforce strong authentication with user roles and 2FA.
  4. Harden wp-config.php and .htaccess files.
  5. Limit information disclosure in error messages and public APIs.
  6. Implement a web application firewall (WAF) to block attacks.

By following these steps consistently across all of your WordPress sites, you can greatly reduce the risk of a successful attack. However, it‘s important to remember that security is never a "set it and forget it" proposition.

New vulnerabilities and attack techniques are constantly emerging, so it‘s crucial to stay informed and adapt your security strategy accordingly. Keep an eye on trusted sources like the WordPress Security Mailing List and reputable security blogs for the latest updates.

As a professional WordPress developer, you have a unique opportunity to contribute to the security of the entire ecosystem. If you discover a new vulnerability or security issue, be sure to report it responsibly to the WordPress security team or the relevant plugin/theme developer.

By working together as a community and prioritizing security in everything we do, we can help protect the millions of businesses, organizations, and individuals that rely on WordPress every day. It‘s a big responsibility, but one that‘s well worth the effort.

Similar Posts