Trusted Bespoke Software & eCommerce Solution Developers

Trusted Bespoke Software & eCommerce Solution Developers.

Preventing WordPress Hacks: A Secure Setup Approach

WordPress, the web’s beloved content management system (CMS), powers a staggering 43.2% of all websites on the internet. Its user-friendly interface and abundant selection of plugins and themes have made it the go-to choice for bloggers, small businesses, and even Fortune 500 companies. However, this ubiquity also makes it an attractive target for hackers. In fact, as reported by Wordfence, a leading WordPress security plugin, over 1.6 million WordPress sites were hit with 13.7 million attacks in just 36 hours, originating from 16,000 different IP addresses.

The rising trend of cyberattacks on WordPress websites emphasizes the importance of a secure setup. Hackers, equipped with ever-evolving techniques and malicious intent, often exploit vulnerabilities to infiltrate and compromise these sites. The consequences of such breaches can be devastating, ranging from data theft and defacement to a loss of customer trust.

In this comprehensive guide, we’ll walk you through the critical steps required to establish a robust and secure WordPress website. While many resources may focus on basic security, we understand that true protection goes beyond passwords and simple plugin installations. We’ll explore the vital steps required for configuring your server and enhancing your website’s security at a foundational level. By implementing these advanced technical measures, you can drastically reduce the risk of unauthorized access, data breaches, and the potential for crippling downtime.

Choosing a Hosting Provider

Your first line of defense against cyber threats begins with your choice of a hosting provider. According to a report by Sucuri, a leading web security firm, a significant portion of hacked websites can be traced back to inadequate hosting services. Reliable hosting providers prioritize server security, maintain up-to-date software, and perform regular security audits. They offer secure server configurations to guard against common vulnerabilities.

Additionally, a quality hosting provider plays a vital role in reducing your website’s response time. Slow-loading websites not only deter visitors but also signal search engines, such as Google, that your site may not provide a good user experience. Google’s algorithms reward faster websites with higher search rankings, which can be a significant boon to your site’s visibility.

For those with small sites and lacking technical expertise, I recommend choosing a managed WordPress hosting service provider such as Wp Engine or Siteground.

Managed WordPress Hosting Provider - WP Engine

This article is targeted for both hosting types:

  1. VPS & Dedicated Hosting
  2. Shared & Managed Hosting

If you’re on a shared hosting plan, you may find that certain advanced configurations aren’t within your reach. In such cases, we recommend considering a VPS (Virtual Private Server) or managed hosting provider that takes security seriously.

Best Practices for WordPress project setup

Setting up a WordPress project can be a daunting task, especially if you are new to it. However, it is crucial to ensure that your website is secure. In this section, we will discuss the basic and essential steps that you should follow to set up a secure WordPress website. Whether you are creating a new setup or revisiting an existing one, these steps will help you create a setup that adheres to standard practices.

Change Database Table Prefix

Changing your WordPress database table prefixes is a simple yet effective security strategy to thwart potential attacks. Hackers often target databases with the default “wp_” prefix, making your site more vulnerable. By altering this prefix, you add an extra layer of security, making it significantly harder for attackers to guess the table names and structure, thus reducing the risk of a successful breach. It’s a proactive measure that fortifies your site’s defenses against common WordPress vulnerabilities.

You can change the table prefix in the initial setup process by either adding the prefix in the wp-config.php or in the database connection screen. If you have already an existing site and would want to change the table prefix, click here.

wp-config.php:

				
					
/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each
* a unique prefix. Only numbers, letters, and underscores please!
*/
$table_prefix  = 'wp_';

				
			

Change Database Table Prefix for Existing WordPress Website

Change the table prefix in wp-config.php

Open either File Manager or FTP Client or shell Access locate the file wp-config.php, and edit the file.

Replace ‘wp_’ with something else; in this case, we replaced it with ‘q2sds1_’

Save the file and exit.

				
					
/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each
* a unique prefix. Only numbers, letters, and underscores please!
*/
$table_prefix  = 'q2sds1_';

				
			
Change the table prefix in the database

Access your database either from PhpMyAdmin or MySQL terminal.

  1. Click on the database name in the menu to the left to show all tables.
  2. Select all tables that start with the table prefix wp_
  3. Click With selected to open the drop-down menu and select Replace table prefix.
  4. Type in wp_ in the From-field, and the new name in the To-field, in this example, q2sds1_.
  5. Click Continue to make the change.
[Resolved] How to replace WordPress database table prefix to avoid WordPress malware attack

SQL command to rename tables:

				
					ALTER TABLE old_table RENAME new_table;
				
			
Replace all references to the old prefix

In the WordPress database, some settings still refer to the old table prefix. To change the prefix completely, you must replace these with the new prefix.

Run the SQL command below to update the references.

				
					# Replace the prefix with your database table prefix
update q2sds1_usermeta set meta_key = 'q2sds1_capabilities' where meta_key = 'wp_capabilities';
update q2sds1_usermeta set meta_key = 'q2sds1_user_level' where meta_key = 'wp_user_level';
update q2sds1_usermeta set meta_key = 'q2sds1_autosave_draft_ids' where meta_key = 'wp_autosave_draft_ids';
update q2sds1_options set option_name = 'q2sds1_user_roles' where option_name = 'wp_user_roles';
				
			

Don't use common username for admin

Avoid using common usernames like “admin” and “system” for the admins. We will disable lookup of username with WordFence in the later section of this article.

Hide WordPress Login Url

Altering your WordPress login URL from the default “/wp-admin” can be a crucial step in securing your website. By doing so, you make it harder for potential attackers to find your login page, reducing the risk of brute force attacks. Changing the login URL adds an extra layer of protection, enhancing your site’s security posture and helping you stay one step ahead of malicious actors. Use WPS Hide Login plugin to hide the login URL.

Add 2FA to the Admin Logins

Enabling Two-Factor Authentication (2FA) for your WordPress site is a vital security measure. It adds an extra layer of protection by requiring users to provide a second form of verification beyond their passwords, such as a unique code sent to their mobile device. This simple yet effective strategy significantly reduces the risk of unauthorized access, even if login credentials are compromised. With 2FA in place, your WordPress site becomes substantially more resilient against hacking attempts, ensuring peace of mind for both you and your users. Use plugins like Wordfence for 2FA.

Check File & Directory Permissions

Ensure the file and directory permissions are correct.

				
					chown www-data:www-data  -R * # Let Apache be owner
find . -type d -exec chmod 755 {} \;  # Change directory permissions rwxr-xr-x
find . -type f -exec chmod 644 {} \;  # Change file permissions rw-r--r--
				
			

Security measures for VPS & Dedicated Hosting

Disable Server Header

Hiding your server name from the HTTP request is a vital security practice as it conceals sensitive information about your server software and version, making it more challenging for potential hackers to exploit known vulnerabilities. By removing the server header, you minimize the risk of attackers targeting specific software weaknesses. It’s the first crucial step toward enhancing your server’s security and safeguarding your WordPress website against potential threats. 

Edit the following file:

				
					nano /etc/apache2/conf-available/security.conf
				
			

In that file, you’ll see several ServerTokens. Make sure they are all commented out and only Prod appears. Also, turn off ServerSignature.

				
					# ServerTokens
# This directive configures what you return as the Server HTTP response
# Header. The default is 'Full' which sends information about the OS-Type
# and compiled in modules.
# Set to one of:  Full | OS | Minimal | Minor | Major | Prod
# where Full conveys the most information, and Prod the least.
#ServerTokens Minimal
ServerTokens Prod
#ServerTokens Full

#
# Optionally add a line containing the server version and virtual host
# name to server-generated pages (internal error documents, FTP directory
# listings, mod_status and mod_info output etc., but not CGI generated
# documents or custom error documents).
# Set to "EMail" to also include a mailto: link to the ServerAdmin.
# Set to one of:  On | Off | EMail
ServerSignature Off
# ServerSignature On

				
			
				
					# Restart apache server
sudo service apache2 restart
				
			

You will notice now that the server header removes the server version from the HTTP request but the name still remains. To override the server name follow the below instructions.

				
					curl -v http://localhost:80/ | head
				
			
				
					< HTTP/1.1 200 OK
< Date: Mon, 25 Jan 2021 09:20:03 GMT
* Server Apache is not blacklisted
< Server: Apache
				
			

Install security module:

				
					sudo apt-get install libapache2-mod-security2
				
			

Enable the module and restart the apache server.

				
					sudo a2enmod security2
sudo service apache2 restart
				
			

Edit /etc/apache2/apache2.conf file.

				
					<IfModule security2_module>
    SecRuleEngine on
    ServerTokens Min
    SecServerSignature "Name of your choice"
</IfModule> 
				
			

Then restart the apache server.

				
					sudo service apache2 restart
				
			

Now when you run the command:

				
					curl -v http://localhost:80/ | head
				
			

You will get

				
					< HTTP/1.1 200 OK
< Date: Mon, 25 Jan 2021 09:31:11 GMT
* Server  is not blacklisted
< Server: Name of your choice
				
			

Server Side Include

Server Side Include (SSI) has a potential risk of increasing the load on the server. If you are using shared hosting or have a web application with heavy traffic, it is recommended to consider disabling SSI by adding Includes in the Options directive.

An SSI attack can lead to the exploitation of a web application by injecting scripts into HTML pages or executing codes remotely. Therefore, it is crucial to take necessary measures to ensure the security of your web application.

				
					<Directory /your/website/directory>
    Options -Includes
</Directory>
				
			

Then restart the apache server.

				
					sudo service apache2 restart
				
			

Disable Directory Listing

Enabling directory listing allows anyone to view the entire directory contents. This means that an attacker can easily discover and access any file, which could lead to the decompilation and reverse engineering of an application. By obtaining the source code, the attacker can analyze it for possible security flaws or gain access to sensitive information such as database connection strings and passwords to other systems. To prevent this, you can disable directory listing by editing the Options directive in the Apache configuration file.

				
					<Directory /your/website/directory>
    Options -Includes -Indexes
</Directory>
				
			

Then restart the apache server.

				
					sudo service apache2 restart
				
			

Set cookie with HttpOnly and Secure flag

You can prevent the most common cross-site scripting attacks by using the HttpOnly and Secure flags in cookies. Without these flags, web application sessions and cookies can be stolen or manipulated, which is dangerous.

Enable header module for header modifications:

				
					sudo a2enmod headers
				
			

Then, add the header to the /etc/apache2/apache2.conf file

				
					Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure
				
			

Then restart the apache server.

				
					sudo service apache2 restart
				
			

Clickjacking Attack

Web application vulnerabilities can put users’ personal information and data at risk, and one of the most well-known types of these vulnerabilities is clickjacking. In clickjacking attacks, a hacker tricks a user into clicking on an element of a website that is actually hidden or disguised as something else, such as a button or link. This can allow the hacker to gain access to sensitive information or perform actions on the user’s behalf without their knowledge or consent.

				
					Header always append X-Frame-Options SAMEORIGIN
				
			

Then restart the apache server.

				
					sudo service apache2 restart
				
			

X-XSS Protection

Cross-Site Scripting (XSS) protection can be bypassed in many browsers. One should apply this protection to a web application even if it has been disabled by the user.

				
					Header set X-XSS-Protection "1; mode=block"
				
			

Then restart the apache server.

				
					sudo service apache2 restart
				
			

Force all connections over TLS

You can then add the following to your site’s .conf file.

				
					<IfModule mod_headers.c>
Header always set Strict-Transport-Security "max-age=15768000; includeSubDomains; preload"
</IfModule>
				
			

Configure Apache to send a 301 redirect for requests to the TLS version of the site:

				
					<VirtualHost 192.168.1.1:80>
    [...]
    ServerName example.com
    Redirect permanent / https://example.com/
</VirtualHost>
				
			

Security Measures for all Hosting Types

Configure a Web Application Firewall (WAF)

Cloudflare‘s Zone-level Web Application Firewall (WAF) is designed to detect and mitigate any malicious requests across all traffic under a specific zone. I highly recommend using the Cloudflare firewall because it can handle all basic and most troubling attacks. Additionally, we can customize firewall rules to fit our specific requirements.

If for any reason, you can not use CloudFlare, install Wordfence to your WordPress website for firewal and malware detection & prevention.

[Resolved] How to Fix a hacked WordPress website with CloudFlare WAF(We application firewall)

Enable Malware Detection Tool

Enable Wordfence firewall and configure the options to match your requirements.

[Resolved] How to remove malware from WordPress website

Schedule regular website scans to detect malware and respond immediately.

Conclusion

A secure WordPress setup is a crucial foundation for any website. By choosing a reputable hosting provider, installing WordPress securely, employing essential security plugins, managing user roles, protecting against brute force attacks, maintaining regular backups, monitoring your site, enabling SSL and HTTPS, and providing security education, you’re setting your website on the path to a more secure future. Take action now to secure your site and protect your valuable content and online presence from potential threats.

This comprehensive guide will help you create a solid security strategy for your WordPress website, safeguarding it from hacks and vulnerabilities. Don’t wait until it’s too late; secure your site today!

Abhijit Das
CEO & Co-Founder
Table of Contents

Are you looking for a reliable & trustworthy technology vendor for your organization?

These brands trust us for their enterprise app & modernization requirements.

Recommended Posts

Let’s transform your business

We have successfully launched 50+ apps for businesses from all around the world. We take pride in our ability to deliver quality apps on time and within budget.