Secure Your WordPress Website with Code Examples: A Guide to Protecting Your Website

Website security is crucial in today’s digital landscape, and WordPress is no exception. A lack of security can lead to malicious attacks, such as hacking or spamming, which can harm your website’s reputation and cause financial losses. In this tutorial, we’ll outline steps you can take to secure your WordPress website and provide code examples for each step.

Before proceeding with any customizations in WordPress, it’s essential to set up a child theme. A child theme acts as a safe and efficient way to make modifications without affecting the parent theme. If you haven’t set up a child theme yet, follow this tutorial on How to Create a Child Theme for Customization. It will guide you through the process and ensure that your customizations remain intact even after theme updates.

Use Strong Passwords

The first line of defense against hacking attempts is a strong password. Use a combination of letters, numbers, and symbols to create a password that is difficult to guess. Avoid using easily accessible information, such as your name or birthdate. A password manager can help generate and store secure passwords.

The code provided can be added to your child theme’s functions.php file or a custom plugin. This will ensure that whenever a password is set or reset, it’s generated with strong security.

function set_strong_password($user_id) {
    $password = wp_generate_password(12, true, false);
    wp_set_password($password, $user_id);
}
add_action('user_register', 'set_strong_password'); // Hook for new user registration
add_action('profile_update', 'set_strong_password'); // Hook for profile updates
Code language: PHP (php)

Explanation:

  • wp_generate_password(12, true, false); generates a 12-character password with special characters, ensuring strong security.
  • wp_set_password($password, $user_id); sets the generated password for the specified user ID.
  • add_action('user_register', 'set_strong_password'); ensures strong passwords for new user registrations.
  • add_action('profile_update', 'set_strong_password'); ensures strong passwords when user profiles are updated.

Keep Your WordPress Core, Themes, and Plugins Up-to-Date

Updates often include security patches that address known vulnerabilities. Therefore, it’s essential to keep your WordPress core, themes, and plugins up-to-date. Regularly log in to your WordPress dashboard to check for updates, or set up automatic updates for added convenience.

Add the following line to your wp-config.php file to enable automatic updates for the WordPress core:

define( 'WP_AUTO_UPDATE_CORE', true );
Code language: PHP (php)

Use a Secure Connection (SSL)

A Secure Socket Layer (SSL) certificate encrypts information transmitted between your website and its visitors, protecting sensitive data such as login credentials and payment information. Obtain a free SSL certificate from Let’s Encrypt or purchase one from your web hosting provider. Once installed, configure WordPress to enforce SSL on all pages. After obtaining an SSL certificate (usually from your hosting provider or Let’s Encrypt), configure WordPress to force SSL on all pages to ensure secure browsing.

Add this to your wp-config.php file to forces all WordPress admin sessions to use HTTPS, ensuring that data exchanged between the browser and server is encrypted.

define( 'FORCE_SSL_ADMIN', true );
Code language: PHP (php)

Use a Firewall

A firewall adds an extra layer of security by monitoring and controlling incoming and outgoing traffic to and from your website. It can block malicious IP addresses and prevent potential threats. Install and configure a firewall plugin like Wordfence or Sucuri from the WordPress plugin repository.

Manual Configuration (Optional .htaccess Rules):

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

# BEGIN Additional Security Rules
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_URI} ^/wp-admin [NC,OR]
RewriteCond %{REQUEST_URI} ^/wp-login [NC]
RewriteRule .* - [F]

RewriteCond %{QUERY_STRING} (eval\() [NC,OR]
RewriteCond %{QUERY_STRING} (\.\.\/) [NC,OR]
RewriteCond %{QUERY_STRING} (base64_encode) [NC,OR]
RewriteCond %{QUERY_STRING} (localhost|loopback|127\.0\.0\.1) [NC,OR]
RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (<|%3C).*script.*(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (javascript:|<|%3C).* [NC,OR]
RewriteCond %{QUERY_STRING} (|%0A) [NC,OR]
RewriteCond %{QUERY_STRING} (|%0D) [NC,OR]
RewriteCond %{QUERY_STRING} \.\./ [NC,OR]
RewriteCond %{QUERY_STRING} ( |%20) [NC,OR]
RewriteCond %{QUERY_STRING} (;|<|>|'|"|\)|%0A|%0D|%22|%27|%3C|%3E|%00).*(/\*|union|select|insert|drop|delete|update|cast|create|char|convert|alter|declare|order|script|set|md5|benchmark|encode) [NC]
RewriteRule .* - [F]
</IfModule>
# END Additional Security Rules
Code language: PHP (php)

Explanation:

  • The .htaccess rules add additional security by blocking access to sensitive WordPress files (wp-admin, wp-login.php) and filtering out malicious query strings that could indicate hacking attempts.

Back Up Your Website Regularly

Regular backups are essential to mitigate the impact of potential security breaches, server failures, or accidental data loss. Ensure you have recent backups stored securely. Install and configure a backup plugin like UpdraftPlus to automate backups and store them in a secure location, such as remote servers or cloud storage.

Add it to functions.php to ensure that UpdraftPlus creates automatic backups before any updates are performed, providing a safety net against update failures or data loss.

add_filter( 'updraftplus_autobackup_default', '__return_true' );
Code language: PHP (php)

Disable File Editing

Prevent unauthorized access to your site’s files by disabling the built-in file editor in the WordPress admin dashboard.

Add the following line to your wp-config.php file:

define('DISALLOW_FILE_EDIT', true);

That’s it! By following these steps and implementing the provided code examples, you can significantly enhance the security of your WordPress website. Regularly updating core software, using strong passwords, enabling SSL, deploying a firewall, and maintaining backups are fundamental practices for safeguarding your site against potential threats. If you’re unsure about implementing any security measures, consider consulting with a professional WordPress developer to ensure comprehensive protection.

Secure your WordPress website today to maintain its integrity, protect user data, and uphold your online reputation.

Leave your feedback and help us improve ๐Ÿถ

We hope you found this article helpful! If you have any questions, feedback, or spot any errors, please let us know in the comments. Your input is valuable and helps us improve. If you liked this article, please consider sharing it with others. And if you really enjoyed it, you can show your support by buying us a cup of coffee โ˜•๏ธ or donating via PayPal ๐Ÿ’ฐ.

More free knowledge, because why not?

Your thoughts matter, leave a reply ๐Ÿ’ฌ

Your email address will not be published. Required fields are marked *