Best WordPress Security Tips 2022: Server, CMS, Database Settings
What's up SEOs! Today I want to talk on improving our favorite WordPress engine, which has become a reliable friend and parent of our blogs to me and hopefully to you as well.
Today will be disclosed a very important problem - security. Agree that this is almost the most important aspect of doing business on the Web and not only. So I recommend you not to miss this publication and by all means to read the recommendations described below. And then you will be able to sleep a little better ;) No kidding!
In this post, we're going to break down exactly 10 useful tips on how to improve the security of our WordPress blogs in various ways.
Before the description even begins, I'd like to advise you to check out my other publications on the topic of improving WordPress as well. I promise that everyone who cares about the fate of his native blog will find something useful, important and interesting.
1. Removing unnecessary information from the screen
Problem:
When you suddenly can not log into your blog, WordPress displays some information that the error. This is of course good if you've forgotten your password, but it can also be useful to someone who's plotting to hack your blog! So why not go ahead and disable the display of login error messages?
Solution:
To remove login error messages, simply open the functions.php file in our design theme and insert the following code at the very beginning:
add_filter('login_errors',create_function('$a', "return null;"));
Save it and go check it out. There, no errors now ;)
Explanation:
This code simply adds a loop to rewrite the login_errors () function. The error message will now produce a clean array, since the function we made returns an empty value.
2. Using Secure Connection, Installing an SSL Certificate
Problem:
If you are worried about data being intercepted, you should definitely start using SSL. In case you don't know what it is, SSL is an encrypted protocol that secures data transmission on networks such as the Internet, for example.
A secure connection protects data transmitted by visitors to the site over the Internet. Install a free or paid certificate, a green padlock appears in front of the site address, and the data transfer protocol changes from http to https.
Did you know that WP can be forced to use SSL? Not all hosting sites allow SSL, but hopefully yours does ;)
If you have registration / user authorization or payment acceptance on your site, that is, the transfer of personal data, then you need to install an SSL certificate.
As of January 1, 2017, an established SSL certificate became one of the ranking factors for Google websites.
Solution:
Switching the site to secure connection using wp-config.php file:
First, check that the server supports SSL (the easiest way is to ask the administrator, but most likely you already have SSL enabled). Then open wp-config.php file at the root (where WordPress itself is installed and where index.php is) and insert the following code:
define('FORCE_SSL_ADMIN', true);
To switch the site using .htaccess, add this code:
< IfModule mod_rewrite.c >
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
< /IfModule >
Now save it - and that's it!
Explanation:
Well, there's nothing complicated here. WordPress has a bunch of regular expressions to customize. In this case, we simply defined FORCE_SSL_ADMIN and set it to true. And as a result the engine started using a secure SSL connection.
3. Using .htaccess to Protect the wp-config File
Problem:
Like any SEO expert who configures WP for his projects, you should understand the importance of the wp-config.php file. This file contains all the data needed to access the Database: username, password, server data, etc. Protecting wp-config.php is essential, so how about using Apache features?
Solution:
Find file .htaccess located in the root (where index.php). Just in case, create a copy of the file, otherwise what if anything ... Open the file and insert the following code:
< files wp-config.php >
order allow,deny
deny from all
< /files >
Explanation:
.htaccess is a powerful and best tool to prevent unwanted access to certain files on your server. In the code above we have created a rule that prohibits any attempt to access the file wp-config.php, so that no hellfire daemons will get access to it!
4. Blocking Undesired Users and Bots
Problem:
This rule works both online and in real life: if someone who pesters you today is likely to pester you tomorrow. Do you know how many spam bots come back to your blog ten times a day to post their fucking comments? The solution to that problem is simple - let's shut them off from your blog!
Solution:
Add the following code to our .htaccess file, located in the root:
< Limit GET POST PUT >
order allow,deny
allow from all
deny from 123.456.789
< /LIMIT >
Change 123.456.789 to the real ip address of the person you want to block.
Explanation:
Once again we see that Apache is a powerful tool, which in this case allows us to allow access to the blog to everyone except people or bots with a specified IP.
To block multiple ip-addresses you can use the following entry:
< Limit GET POST PUT >
order allow,deny
allow from all
deny from 123.456.789
deny from 93.121.788
deny from 223.956.789
deny from 128.456.780
< /LIMIT >
5. Protecting Your Wordpress Site from WEB Injection Attacks
Problem:
Protecting a dynamic site is especially important. Many developers protect GET and POST requests, but sometimes that is not enough. We too will try to protect our blog from injections and any attempts to change the PHP variables GLOBALS and _REQUEST.
Solution:
The following code will block injections and attempts to change variables. It should be inserted into the .htaccess file:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
RewriteRule ^(.*)$ index.php [F,L]
Explanation:
Using the features of .htaccess we can check the requests. What we have done is check if the request contains <script> and if it tries to change the value of the GLOBALS and _REQUEST variables. If there is anything like that, the request is blocked and a 403 error is thrown in the browser.
6. Fighting Parsers and Scrapers.
Problem:
If your blog is more or less well-known, people will no doubt try to use your content on their sites without our consent. And one of the biggest problems with that is the use of your pictures, which causes more traffic and load on the server.
Solution:
To protect your blog against these evil actions, you need to add code to your .htaccess file. Again, don't forget to make a backup copy of the file.
RewriteEngine On
#Replace ?example\.com/ with your blog url
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?example\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
#Replace /images/nohotlink.jpg with your "don't hotlink" image url
RewriteRule .*\.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L]
After the above steps, only your web server will be able to use links to your images, or, even more correctly, whoever decides to use images from your server will have to save them first and then upload them to their server, which makes stealing more difficult and time-consuming.
Sites that will link to your pictures will automatically show nohotlink.jpg. Be careful, you need to prepare this image in advance, so that it will be displayed on the sites of villains =)
Explanation:
With this code, the first thing we did was to check that the referrer matches the URL of our blog and that it isn't empty. If it isn't and the requested file has the extension JPG, GIF, BMP or PNG, it will display a pacifier picture instead.
7. Creating a Plugin Protecting Your Site from Malicious URL Requests
Problem:
Hackers and other bad guys often use all sorts of bad queries to find bottlenecks and attack. WordPress has a pretty good initial protection, but there's no limit to perfection!
Solution:
Create a text file and add the following code. Save the file as blockbadqueries.php. After that we upload it to the directory wp-content/plugins and activate our plugin through the admin as any other. Now our blog is protected from malicious requests.
<?php
/*
Plugin Name: Block Bad Queries
Plugin URI: https://perishablepress.com/block-bad-bots/
Description: Protect WordPress Against Malicious URL Requests
Author URI: http://perishablepress.com/
Author: Perishable Press
Version: 1.0
*/
global $user_ID;
if($user_ID) {
if(!current_user_can('level_10')) {
if (strlen($_SERVER['REQUEST_URI']) > 255 ||
strpos($_SERVER['REQUEST_URI'], "eval(") ||
strpos($_SERVER['REQUEST_URI'], "CONCAT") ||
strpos($_SERVER['REQUEST_URI'], "UNION+SELECT") ||
strpos($_SERVER['REQUEST_URI'], "base64")) {
@header("HTTP/1.1 414 Request-URI Too Long");
@header("Status: 414 Request-URI Too Long");
@header("Connection: Close");
@exit;
}
}
}
?>
Explanation:
This code is quite simple. It checks for excessively long requests (more than 255 characters) and checks for the presence of eval or base64 php functions in the URI. If one of the conditions is met, the plugin sends a 414 error (for those who don't know: 414 Request-URI Too Long).
8. Removing the Version of Wordpress Engine, Scripts and Styles
Problem:
As you probably know, WordPress automatically displays the current version of the engine you're using. It's not safe if you don't promptly update to the current version (although it's strictly recommended by the developers, but let's face it, we all do it). That's why it's worth making life difficult for hackers!
By default, Wordpress leaves meta tags with the current version on site pages. This is done to keep track of the number of sites running on Wordpress. The same information is used by hackers to break into the site, using descriptions of vulnerabilities of outdated versions of the software, which are publicly available
Solution:
Add the following line to your theme's functions.php file. Save, refresh the page and voila - no more version number.
/* Removing the Version of Wordpress Engine */
function remove_version_info() {
return '';
}
add_filter('the_generator', 'remove_version_info');
/* Removing the Version of the Scripts and Styles*/
function remove_wp_version_strings( $src ) {
global $wp_version;
parse_str(parse_url($src, PHP_URL_QUERY), $query);
if ( !empty($query[‘ver’]) && $query[‘ver’] === $wp_version ) {
$src = remove_query_arg(‘ver’, $src);
}
return $src;
}
add_filter( ‘script_loader_src’, ‘remove_wp_version_strings’ );
add_filter( ‘style_loader_src’, ‘remove_wp_version_strings’ );
?>
The script below removes just the version of the WP engine.
remove_action('wp_head', 'wp_generator');
Explanation:
9. Changing the Default CMS Administrator Name - the "admin"
Problem:
During the installation of Wordpress, the site administrator is given the default name Admin. If you leave it as it is, hackers will know half of the login information, because the names Admin, Administrator, Root or domain name are tried first by hackers when trying to pick up a login and password to enter the site.
Bruteforce is one of the easiest ways to hack a password. The method is simple: try random passwords as many times as possible until the right one is found. Brutforce uses dictionaries that provide many different combinations of passwords.
But knowing the username definitely makes it a lot easier to find the right username-password combination. That's why we need to change the standard "admin" to something more complicated.
If you change the default admin name to a different one, hackers will have to pick up both username and password.
If the username and login are the same, the hacker already knows half the information to get into the site. Select a different name from the Display as drop-down list and click Update Information.
Instead of Very-strong-username, you should have your unique complex login name. You can change the administrator name manually in the database, or you can create a new administrator and delete the old one.
If you create a new administrator, this may cause some plugins not to have access to some features because the new administrator did not get the appropriate permissions. Therefore, changing the name of the administrator in the database is considered a better way.
By the way, WordPress 3.0 allows you to change the name through the admin. Therefore, this point is important if you are using an old version of WP and an old "admin" account.
Solution:
Just run the following SQL query for your database, for example through phpMyAdmin:
UPDATE wp_users SET user_login = 'NewUsername' WHERE user_login = 'Admin';
10. Prevent Browsing Server Folders/Directories
Problem:
On Linux and Unix servers, files and folders have permissions that allow or deny different users access to files and folders on the server. If some files or folders have too low permissions, hackers can take advantage of this and gain some control over the site.
By default, most web hosts allow directory listing. So, for example, if you type sitename.com/wp-includes in the browser you can see the directory files. This is a potential risk of danger.
Solution:
File and folder access rights:
Provide to all files and folders permissions of 644 and 755. Add this code to wp-config.php:
/* Files and folders permissions */
define('FS_CHMOD_FILE', 0644);
define('FS_CHMOD_DIR', 0755);
Manually give the wp-config file 400 rights. If the site becomes inaccessible, change it to 440.
The following files and folders can also be given downgraded rights:
- Root folder — /example.com/public_html/ — 750
- .htaccess — /example.com/public_html/.htaccess — 640
- wp-admin/ — /example.com/public_html/wp-admin — 750
- wp-admin/js/ — /example.com/public_html/wp-admin/js/ — 750
- wp-admin/index.php — /example.com/public_html/wp-admin/index.php — 640
- wp-content/ — /example.com/public_html/wp-content — 750
- wp-content/themes/ — /example.com/public_html/wp-content/themes — 750
- wp-content/plugins/ — /example.com/public_html/wp-content/plugins — 750
- wp-includes/ — /example.com/public_html/wp-includes — 750
Also add the following line to the Apache configuration or .htaccess file:
Options -Indexes
Explanation:
Keep in mind that this is not the same as adding Disallow: /wp* to the robots.txt file. This will not disallow indexing of the directory, but will disallow browsing by users.
11. Deleting the readme.html file and other Unused Files
Problem:
While you are stillinside the server settings, delete any unneeded files after installation
Solution:
- readme.html
- wp-config-sample.php
- /wp-admin/install.php
- /wp-admin/upgrade.php change the file name to something else, such as upgrade-1.php, but do not delete, this file may be needed.
12. Changing Database Prefix
Problem:
By default, all tables in the database begin with the prefix wp_. If you leave it as it is, it will be easier for hackers to get into your site or database, because most Wordpress sites have the same table names and the same prefix.
Solution:
Change in wp-config.php:
This file is in the root folder of the site, download it to your computer using an ftp-client or file manager on the hosting.
Open the file, find this line:
< ?php
/**
* Tables Prefix in the WordPress Database.
* .....
*/
$table_prefix = 'wp_';
Change wp_ to something unique, but it is recommended to leave the underscore at the end. The prefix can contain numbers, letters, and an underscore, such as db123_, qwerty_db_, etc...
Save the file and upload it back to the server. If you now try to access the site, it will be unavailable. It should be, because now the data in the database does not match the data in the file wp-config.php.
13. Disabling XML-RPC
Problem:
XML-RPC is an API that is used by Wordpress for remote site access, for trackbacks and pingbacks, and is used by the Jetpack plugin. Leave it on if you use any of these, or turn it off if you don't, as hackers can crawl passwords by the thousands through the xmlrpc.php file.
Even if you use complex passwords, brute-force attacks consume a lot of server resources. If your site is on low-cost hosting, such an attack may cause the site to freeze due to overuse of all server resources.
Solution:
To disable XML-RPC, add this rule to .htaccess:
< Files xmlrpc.php >
Order Allow,Deny
Deny from all
< /Files >
14. Using Secure FTP (SFTP), or SSH
Problem:
Transferring files via FTP is a quick and convenient way if you are editing or adding some files to the site, but this method is not so secure because hackers can intercept the FTP connection.
Solution:
Using SFTP is more secure because the data transmitted is encrypted, making it much harder for hackers to intercept the login and password. SSH is another secure way to add or move site files.
If you do not plan to use FTP, you can delete all FTP accounts so that hackers have nothing to hack. On some hosting sites, you can set a time limit on the use of FTP accounts, that is, after a certain period of time the account will be deleted.
To enable SFTP, create this connection on the hosting site and add this line to wp-config.php before the "That's all, no further editing" line.
define('FTP_SSL', true);
15. Checking PHP and MySQL Versions
Problem:
If you use older versions of software, it slows down the site. If you use even older, unsupported versions of software, this can lead to the site being compromised by lists of outdated software vulnerabilities that are publicly available.
Make sure that your web hosting service uses PHP and MySQL version 5.6 or higher. Wordpress recommends PHP 7.4.
16. Disable displaying of PHP Version in Server Responses
Problem:
Just like with the software version, it is better to hide the PHP version you are using. Add this code to .htaccess. If it does not work, contact technical support for hosting, ask to disable showing the version of php in the server settings:
Solution:
< IfModule mod_headers.c >
Header unset X-Powered-By
Header unset Server
< /IfModule >
17. Disabling the File Editor in the Admin Panel
Problem:
Many SEOs and Web Masters consider access to editing files in the Wordpress panel dangerous, because if a hacker gets into the admin area of the site, they will have access to those files.
Solution:
Perhaps the ban on editing php files in the admin area will give you some time to try to regain control of the site. To turn off file editing in the admin panel, do the following:
/* Disabling file editing in the WP admin */
define('DISALLOW_FILE_EDIT', true);