WordPress powers over 43% of websites globally, making it a prime target for cyberattacks. Securing your website is essential not only to protect your data but also to maintain user trust and avoid penalties from search engines.

Many articles suggest turning off some of WordPress features as a way to enhance security, but this is not the best approach. In this guide, we will show you how to reduce the risk of security-related problems on your WordPress site without compromising its performance or functionality.

Install Only Necessary Plugins

According to data from the popular security plugin Wordfence, WordPress security is often compromised due to the use of plugins. It doesn’t matter whether the plugin comes from a trusted developer or not; if it’s poorly coded, it can expose your website to attacks.

A recent vulnerability report from Wordfence revealed that the WP Statistics plugin, version 13.2.16 or below, was vulnerable to SQL injection attacks due to insufficient escaping of user-supplied parameters and inadequate preparation of SQL queries. This is just one example, but Wordfence’s database shows that plugins are frequently the most vulnerable part of a WordPress site. That’s why it’s recommended to install only essential plugins, as this can significantly reduce the risk of security-related problems.

Disable the Generator Tag

Disabling the generator tag is a common security tip that you’ll find in many guides. Most posts recommend this because the tag exposes the WordPress version number, but that’s not the real issue. WordPress core is very secure, so disclosing the version isn’t necessarily a risk.

The real concern is that some plugins use the generator tag to reveal their presence and version number, and since plugins are often a source of vulnerabilities, it’s wise to disable this feature. This prevents attackers from identifying and exploiting known plugin vulnerabilities.

add_action('init', 'disable_generator_tag');

function disable_generator_tag() {
    remove_action('wp_head', 'wp_generator');
}

Disable wp-json API (If Not in Use)

The wp-json API is useful for many WordPress plugins, such as WooCommerce and Contact Form 7, so you shouldn’t disable it if your site relies on these. However, if no plugins on your site use this feature, it’s safe to disable the API.

Disabling the API reduces the attack surface and can help improve performance by preventing unnecessary external requests.

add_filter( 'rest_authentication_errors', 'wp_json_authentication' );

function wp_json_authentication( $result ) {
    if ( true === $result || is_wp_error( $result ) ) {
        return $result;
    }

    if ( ! is_user_logged_in() ) {
        return new WP_Error(
            'not_logged_in',
            __( 'Sorry, you must be logged in to make a request.', 'diversifyindia' ),
            array( 'status' => 401 )
        );
    }

    return $result;
}

Use WordPress Nonce in Forms

A nonce (Number used ONCE) is a random alphanumeric string that is valid for a specific period. WordPress uses nonces to protect against Cross-Site Request Forgery (CSRF) attacks, where an attacker tricks you into performing actions like deleting posts or changing settings without your consent.

WordPress nonces expire after 24 hours. If an attacker posts a malicious link and you click it, the link will only work within that 24-hour window, minimizing the damage.

While WordPress core already implements nonces in its forms, if you’re creating custom forms (e.g., contact forms or newsletter sign-ups), it’s best to protect them with WP nonces. If you want to learn how to create forms on a WordPress website, you can read our article on creating a subscription form without using a plugin.

Deny Directory Listing

If the index.html file is missing in any directory, visitors can view all the files and subdirectories on your site. This is a significant privacy risk, as anyone could access your uploads folder and view your media files.

To prevent this, you need to add the following rule to your .htaccess file:

Options -Indexes

Add Security Rules to the htaccess File

There are some .htaccess rules that can enhance the security of your WordPress website. You can apply the following rules to improve your site’s security.

# Deny access to wp-config.php
# The wp-config file contains the database username and password
<FilesMatch "wp-config\.php">
    Require all denied
</FilesMatch>

# Instruct the browser to always use the MIME type declared in Content-Type
# Do not attempt to determine the MIME type based on the file's content
# If this header is not present, an attacker could execute malicious JavaScript files
Header set X-Content-Type-Options "nosniff"

# Instruct the client that this server only accepts HTTPS requests
Header set Strict-Transport-Security "max-age=63072000"

# Block access to PHP files
# Create a separate .htaccess file in the includes directory and add this rule
<FilesMatch "\.php$">
    Require all denied
</FilesMatch>

You can read our article on the most common htaccess rules for enabling browser caching, image hotlink protection, and more.

Block Dangerous PHP Functions

If you’re using VPS hosting, you can edit the php.ini file to block dangerous PHP functions like exec, system, and shell_exec. These functions are often exploited by attackers to execute malicious commands on your server.

Unfortunately, on shared hosting, you may not have access to the php.ini file, so you have to check with your hosting providers to confirm whether these functions are blocked by default. Below is an example of the php.ini configuration used to disable dangerous PHP functions.

; This configuration prevents PHP scripts from executing system commands.
; Add the following functions to the disable_functions list to improve security:
disable_functions = exec, passthru, shell_exec, system, popen, proc_open

One particularly dangerous function, eval, cannot be blocked using the disable_functions directive. To block eval, you need to install the PHP Suhosin extension.

If you cannot block these dangerous functions, avoid using them in any code that processes user-supplied data.

How to Protect From Brute Force Attacks

Brute force attacks, where attackers try multiple username and password combinations to gain access to your site, are a common threat to WordPress security. Unfortunately, WordPress does not come with built-in protection against this type of attack.

To protect your site, you should install a security plugin that limits login attempts, such as Login Attempts Reloaded. Alternatively, you can add custom code to implement this protection yourself, which is often a more secure approach than relying on plugins.

Hackers often use the XML-RPC protocol to perform brute force attacks. While disabling xmlrpc.php may reduce the risk of such attacks, it is not a complete solution to this vulnerability. The better approach is to limit the number of login attempts and address the user enumeration vulnerability.

User enumeration is a technique that hackers use to find valid usernames based on information provided in error messages. For example, if a hacker tries to log in using the username “admin” and that username exists on your website, WordPress will display the error message: ‘The password you entered for the username admin is incorrect’. This message informs the hacker that the username “admin” is valid, encouraging them to launch a brute force attack on that user’s password.

To mitigate this risk, it is recommended to display a generic error message like ‘Login information is incorrect’. This change will make it more difficult for hackers to identify valid usernames and gain unauthorized access to the system.

Security plugins like Wordfence, Sucuri, and Jetpack Protect offer protection against brute force attacks. In addition to this, they also scan your website for viruses and malware. For more information about essential WordPress plugins, you can read our article on must-have plugins for WordPress.

Disable XML-RPC Protocol (If Not Needed)

XML-RPC (Extensible Markup Language Remote Procedure Call) is an API that allows remote management of WordPress sites through apps like Jetpack. However, it’s also a common target for brute force attacks.

By default, WordPress allows unlimited login attempts via XML-RPC, making it a vulnerability. If you install a plugin like Limit Login Attempts Reloaded and set a cap on login attempts, you can safely leave XML-RPC enabled. If you don’t use this feature, you can disable it with the following code:

add_filter('xmlrpc_methods', function($methods) {
    return array();
});

Note that the code above will completely disable the XML-RPC API. There is no need to add extra code to remove the link tag pointing to the xmlrpc.php file in the head section of the HTML.

Take Regular Backups

Regular backups are your best defense against security threats. There are two types of backups you should perform frequently:

  1. Full site backups: This includes all files and folders related to your WordPress website.
  2. Database backups: You can back up your database using phpMyAdmin or the mysqldump command.

Having backups ensures that you can restore your site quickly if something goes wrong. For automated backups, consider using plugins like UpdraftPlus or VaultPress to easily manage and restore your data.

Other Security Enhancements

  • Always use HTTPS: Redirect HTTP traffic to HTTPS to ensure secure communication between users and your website.
  • Enable HTTP Strict Transport Security (HSTS): This security feature helps protect websites against man-in-the-middle attacks by ensuring that browsers only connect via HTTPS.
  • Set a minimum TLS version: Use TLS 1.2 or higher to ensure secure connections and protect against vulnerabilities associated with older versions.
  • Use Cloudflare’s Bot Fight Mode: This feature helps mitigate bot traffic and protect your site from malicious activities.
  • Use Cloudflare’s Web Application Firewall (WAF): A WAF helps filter and monitor HTTP traffic to and from your web application, providing an additional layer of security.
  • Ensure that only essential users have administrator privileges. Also, enable two-factor authentication (2FA) for an added layer of security when logging in.
  • Avoid common usernames like ‘admin’.
  • Use strong passwords to enhance the security of user accounts.
  • Change the default table prefix from wp_ when setting up your database.
  • Make use of the $wpdb->prepare function before executing SQL queries to prevent SQL injection attacks.
  • Always sanitize and validate user input before saving it to your database.
  • Your hosting provider can also offer additional security measures, such as server-level firewalls, automated backups, and malware scanning. Opt for a host with a strong security reputation.
  • Regularly update WordPress core, themes, and plugins to ensure you have the latest security patches. Outdated software is a common entry point for hackers.

Conclusion

By following these steps, you can protect your WordPress site from common security threats without sacrificing performance. Start with the most critical steps, such as limiting login attempts and taking regular backups, then gradually implement the other measures. Your website’s security should be an ongoing priority.

Frequently Asked Questions

Is it possible for a supercomputer to easily hack any website using a Brute Force attack?

No, even with the computational power of a supercomputer, hacking a well-secured website through brute force is not easy. Brute force attacks rely on trying numerous username-password combinations until the correct one is found. While a supercomputer could significantly speed up this process, it doesn’t require both the attacker and the server to have supercomputers.

A well-configured WordPress site with strong passwords, rate limiting on login attempts, and security measures like two-factor authentication will make brute force attacks difficult, regardless of the attacker’s computational power.

How to protect against CSRF attacks?

To protect against Cross-Site Request Forgery (CSRF) attacks, there are two primary steps:

  1. Use Nonces in Forms: Nonces are unique strings generated for each form submission and are verified on the server before processing any data. These nonces change periodically, making it difficult for attackers to reuse them for malicious requests.
  2. Set the SameSite Attribute on Cookies: By configuring the SameSite attribute on cookies, you can limit how cookies are sent in cross-origin requests, reducing the risk of CSRF attacks.

The X-Frame-Options header is useful for preventing click-jacking attacks, which involve embedding your website in a malicious frame, but it’s not a direct solution for CSRF attacks.

How do I hide the WordPress login page?

You can use the WPS Hide Login plugin to change the default login URL of your WordPress site. This helps protect your login page from automated brute force attacks and unauthorized access attempts. It is recommended to protect the login form from anonymous visitors by combining this with other security measures like limiting login attempts or using a CAPTCHA.