Secure your WordPress site: 20 best practices

/
secure wordpress site

WordPress is the most popular CMS in the world, powering over 40% of websites. Unfortunately, this popularity also makes it a prime target for hackers. Every day, thousands of WordPress sites are hacked, resulting in loss of data, time and money for their owners.

But don’t worry, there are many simple and effective measures to strengthen the security of your WordPress site and protect it from threats. In this article, I will share with you the 20 best practices to secure your WordPress site. By following these tips, you can sleep soundly knowing that your site is in good hands. Ready to discover the tips? Let’s go now!

Understand how to secure your site

secure your WordPress site

Understanding the security of your WordPress site is the first step to effectively protect it. Before we go into the specific steps you can take to secure your site, it’s essential to understand why WordPress security is so important, what are the common threats and what could be the consequences of an attack.

Common threats to WordPress sites

SQL Injection: This is a technique used by hackers to manipulate your site’s database by inserting malicious code.

Brute force attacks: These attacks consist of trying a large number of username and password combinations until the correct combination is found.

Cross-site scripts (XSS): This type of attack occurs when malicious scripts are injected into trusted websites, so that the scripts can be used to steal sensitive information.

DDoS attacks: A distributed denial of service (DDoS) attack occurs when your site is flooded with traffic to make it inaccessible.

Exploiting plugin security flaws: Many WordPress sites use plugins to add functionality, but if these plugins are not kept up-to-date, they may have security holes that can be exploited by hackers.

Best practices to secure your WordPress site

best security practices

These practical measures will help you protect your site from potential threats and ensure that your data, as well as the data of your users, remains secure.

The consequences of an attack on a WordPress site

The consequences of an attack on your WordPress site can be disastrous. In addition to the loss of data and time for site restoration, your reputation can be severely affected if your users’ information are exposed. This can lead to a loss of trust on the part of your users and impact on your ranking in search engines. In some cases, you may also be liable for financial loss or damage caused by an attack on your site.

Well, now that you have understood the danger of an unsecured site, it’s time to start fixing this problem!

Enable SSL/HTTPS

And yes!!!! Our first point is SSL or HTTPS, it makes perfect sense for many of us, unfortunately there are still sites without SSL, which is incomprehensible since it has become totally free. If you don’t know how to activate it, contact your host who will do it for you. Once done, remember to go into your WordPress dashboard and click on Settings > General to change your site’s address by adding https:// instead of http:// in both options Web Address (URL) and Website Address (URL).

Once this step is complete, open the . htaccess which is at the root of your site, in your text editor and add this code to it:

RewriteCond %{HTTPS} !=on
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

This will allow to redirect the unsecured URLs to their secure versions.

Use one of the latest PHP versions

There are fewer and fewer compared to a few years ago but there are still some sites that use PHP 5.6 which is so old it no longer has security support and is exposed to unpatched security vulnerabilities. Good hosts don’t even use this version anymore so you’re not likely to encounter this problem, but it doesn’t cost anything to check and update to 8.2 if your host offers it.

Regular update of the WordPress core, themes and plugins

Regularly updating your WordPress site is one of the most effective ways to secure it. The WordPress core, themes and plugins are regularly updated to fix bugs and security vulnerabilities. So make sure you always use the latest version.

To perform updates, simply go to your WordPress dashboard where you will see a notification if an update is available. You can then choose to update automatically or manually.

Implementation of a backup system

Backing up your site is essential for recovery in case of attack. You should have a system in place that makes regular backups of your site. A plugin like UpdraftPlus can make this process easier.

Choice of strong and secure passwords

This should make sense but I have been dealing with customers with a password so simple that it is only a matter of time before they get hacked their sites if they don’t change it now.

Do not use your date of birth or the dates of your loved ones, a strong password is your first line of defense against attacks. Ensure all administrative accounts have unique and complex passwords. Use a combination of letters, numbers and symbols to make your password more robust.

Here is a very useful tool, it allows to keep all your passwords in the same place and generate strong ones: 1Password

Use a secure username

One of the most common mistakes is to use usernames that are easy to guess, such as admin, administrator or test. This exposes your site to a higher risk of brute force attacks. Hackers also use this type of attack to target WordPress sites that don’t have strong passwords. So if this is your case, click on Users > Add New User, select Administrator in Role and enter an easy-to-remember login for you but not for hackers, then delete your old admin account.

Change the login URL of the WordPress administrator

Personnaly, I prefer to use the least possible plugins but to hide the default login page, you would have to modify a core WordPress file that will need to be modified after each update of the one-here, it is for this reason that I strongly recommend the use of the WPS Hide Login plugin which allows you to easily add your own login access.

After installing the plugin, go to Settings > WPS Hide Login and add your login URL and redirect URL.

When someone tries to access your site via wp-admin or wp-login.php, they will be redirected to the redirect URL.

CAREFUL, remember your new login URL otherwise you will not be able to access your administration, yes it would be a shame.

Deepen WordPress security with advanced practices

advanced security

Once you have implemented the basic practices for security of your WordPress site, you may want to consider adopting more advanced security measures. These measures generally require some technical knowledge, but they can provide additional protection against security threats.

Deny access to your wp-config files and . htaccess

The wp-config and .htaccess are two of the most crucial files on your site that give all sorts of permissions and impose restrictions.

Open your. htaccess file and add this code to it right after # END WordPress:

<files wp-config.php>
    order allow,deny
    deny from all
</files>

<Files ~ “^.*\.([Hh][Tt][Aa])”>
     Order Allow,Deny
     Deny from all
     Satisfy all
</Files>

One thing to consider, some plugins like WP Rocket need to write code in its files, I advise you to add their codes manually for more security.

Disable login hints in error messages

By default, the WordPress login page displays an error message when someone enters the wrong username or password. However, these error messages can help hackers guess your username, email address or password.

Enter this code in the functions.php file of your child theme or theme:

function digicommerce_no_wordpress_errors() {
    return 'Wrong username or password !';
}
add_filter( 'login_errors', 'digicommerce_no_wordpress_errors' );

Limit login attempts

We are coming to half of our best security practices, limiting login attempts.

Limiting login attempts can help prevent brute force attacks. You can use a plugin to limit the number of attempts from the same IP address. But as I like to use the least possible plugins, here is the code to add in your theme’s functions.php file to limit the connection to 3 errors:

function digicommerce_check_attempted_login( $user, $username, $password ) {
    if ( get_transient( 'attempted_login' ) ) {
        $datas = get_transient( 'attempted_login' );

        if ( $datas['tried'] >= 3 ) {
            $until = get_option( '_transient_timeout_' . 'attempted_login' );
            $time = digicommerce_time_to_go( $until );
            return new WP_Error( 'too_many_tried',  sprintf( __( '<strong>ERROR</strong>: You have reached the authentication limit, you can try again in %1$s.' ) , $time ) );
        }
    }
    return $user;
}
add_filter( 'authenticate', 'digicommerce_check_attempted_login', 30, 3 ); 

function digicommerce_login_failed( $username ) {
    if ( get_transient( 'attempted_login' ) ) {
        $datas = get_transient( 'attempted_login' );
        $datas['tried']++;

        if ( $datas['tried'] <= 3 ) {
            set_transient( 'attempted_login', $datas , 300 );
        }
    } else {
        $datas = array(
            'tried'     => 1
        );
        set_transient( 'attempted_login', $datas , 300 );
    }
}
add_action( 'wp_login_failed', 'digicommerce_login_failed', 10, 1 ); 

function digicommerce_time_to_go( $timestamp ) {
    // convert mysql timestamp to php time
    $periods = array(
        "second",
        "minute",
        "hour",
        "day",
        "week",
        "month",
        "year"
    );
    $lengths = array(
        "60",
        "60",
        "24",
        "7",
        "4.35",
        "12"
    );
    $current_timestamp = time();
    $difference = abs( $current_timestamp - $timestamp );
    for ( $i = 0; $difference >= $lengths[$i] && $i < count( $lengths ) - 1; $i ++ ) {
        $difference /= $lengths[$i];
    }
    $difference = round( $difference );
    if ( isset( $difference ) ) {
        if ( $difference != 1 ) {
            $periods[$i] .= "s";
            $output = "$difference $periods[$i]";
            return $output;
        }
    }
}

DDoS protection

DDoS attacks are one of the most difficult attacks. Add this code to the htaccess file at the root of your site:

<Files xmlrpc.php>
order deny,allow
deny from all
</Files>

Paste right after # END WordPress.

Prevent Hotlinking

It’s not really security but more optimization against content theft.

What is image hotlinking? It’s literally a person who will take the URL of your image and put it on their own site, so clearly, this will negatively affect your site performance and results. The concern is that it can sometimes be difficult to notice a problem until the wrong thing is done. That’s why it is important to prevent image links in WordPress before this happens.

Add this code to your file . htaccess:

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yoursite.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?google.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?linkedin.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?facebook.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?twitter.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|webp)$ - [F]

Make sure you replace yoursite.com with your website URL. This will prevent sites other than your own site, Google, LinkedIn, Facebook and Twitter from accessing your images. You can of course copy one of its lines and add another URL.

Installation and configuration of a Web Application Firewall (WAF)

A Web Application Firewall (WAF) acts as a shield between your website and incoming traffic. It analyzes traffic and blocks suspicious activities, protecting your site from attacks. WordPress security plugins, such as Wordfence and Sucuri, offer WAF functionality.

Although I strongly advise you to install and configure Cloudflare but it can be technical if you do not have the necessary knowledge.

Disable file editing

WordPress allows administrators to edit theme and plugin files directly from the dashboard. However, this feature can be exploited by malicious people if they get access to your dashboard. You can disable file editing by adding this line of code to your wp-config.php file:

define( 'DISALLOW_FILE_EDIT', true );

Implementation of two-factor authentication

Two-factor authentication (2FA) adds an additional layer of security by requiring a second form of verification when logging in. You can set up 2FA on your WordPress site using a plugin.

Change the default WordPress database prefix

The WordPress database contains and stores all the crucial information needed for your site to work. As a result, hackers often target the database with SQL injection attacks. This technique injects malicious code into the database and can bypass WordPress security measures and retrieve content from the database.

Over 50% of cyber attacks involve SQL injection, making it one of the biggest threats. Hackers are performing this attack because many users forget to change the default wp_ database prefix.

It is quite simple to fix this problem but it is quite complex for a beginner so I advise you to contact your host to ask if he can do it for you.

Hide the WordPress version

Hackers can get into your site more easily if they know which version of WordPress you’re using. They can use vulnerabilities in this version to attack your site, especially if it is an older version of WordPress.

Add this code in the functions.php file of your theme:

function digicommerce_remove_version() {
return '';
}
add_filter( 'the_generator', 'digicommerce_remove_version' );

remove_action( 'wp_head', 'wp_generator' );

Disable the execution of PHP files in some WordPress directories

Another way to strengthen your WordPress security is to disable running PHP files in directories where it’s not needed, such as /wp-content/uploads/.

To do this, open your text editor as Visual Code and add the following code:

<Files *.php>
deny from all
</Files>

Save this file to .htaccess and add it to your /wp-content/uploads/ folder via FTP.

Using a quality WordPress security plugin

A security plugin can add an extra layer of protection to your WordPress site. Plugins such as Wordfence, All-In-One Security, Sucuri Security and iThemes Security offer a range of security features including firewalls, malware scanners, IP blockers and much more.

CAUTION, a mistake not to commit is to activate all the options of a security plugin thinking that the site will become as impenetrable as the pentagon, sorry to tell you but generally, it will have the opposite effect. You should think that a security plugin is a bonus for your site. First of all, you must be on a very good secure host. If not, it may be time to consider migrating.

Site security monitoring and audit

Security monitoring and keeping a log of your site’s activities can help you detect suspicious activity and respond quickly. Several security plugins offer auditing and monitoring features.

Conclusion

By applying these 20 best practices, you will have taken a big step towards a more secure WordPress site. However, remember that security is an ongoing process. Threats are constantly evolving, so staying vigilant and maintaining these good habits over the long term is crucial.

Ready to take action? Implement these tips today and sleep well!

Frequently Asked Questions

Is it really necessary to apply all these security measures on my WordPress site?

Yes, it is strongly recommended that you apply as many of these measures as possible. The more you put in place, the more secure your site will be. However, even if you can’t apply all of them, each measure counts and will enhance the security of your site.

What are the most recommended WordPress security plugins?

Some of the most popular and reliable WordPress security plugins include Wordfence, Sucuri Security, iThemes Security and All In One WP Security & Firewall. Each one has its own strengths and specificities, so it is wise to compare their features to choose the one that best suits your needs.

Is making regular backups of my WordPress site really important for security?

Absolutely! Backups are essential, not only for security but also for the sustainability of your site. In case of hacking or technical problem, having recent backups will allow you to restore your site quickly and easily, thus limiting damage and loss.

Do I have to switch to two-factor authentication for my WordPress site?

Two-factor authentication is not mandatory, but it’s a great practice to significantly enhance the security of your site’s user accounts. This is especially recommended if you have multiple contributors or your site handles sensitive data.

How do I know if my hosting provider is reliable and offers good security measures for my WordPress site?

Choose a reputable hosting provider that puts its security measures (backups, intrusion monitoring, firewalls, etc.). Also check that your hosting offer includes regular updates of the WordPress servers and CMS. Do not hesitate to ask your host directly before subscribing.
Nicolas Lecocq's avatar
I'm Nicolas, the maestro of code at DigiCommerce (yes, I know, modesty smothers me 😁). Fan of WordPress, AI, design and everything related to the web. I love sharing my tips, discoveries and sometimes even my mistakes... so you don’t have to do it yourself!

Subscribe for game-changing tips! (No unicorns included, but the results are just as magical)

Psst... Drop your email here to join our community! Get exclusive insights and proven strategies delivered to your inbox

Similar Articles

migrate wordpress site

6 easy steps to migrate your WordPress site

Migrating your WordPress site can seem like a real headache, especially when you’re not in the business. Between the fear of losing data and that of having your site down…

optimize site speed

8 simple ways to optimize your WordPress site speed

You are tired of your WordPress site that is rowing? To see your visitors leave before they even say “WordPress”? I understand you, WordPress loading speed is a subject that…

We need your opinion !

protected by reCAPTCHA