Speeding up WordPress. How to speed up WordPress
- Translation
Speed and fault tolerance are one of the factors that invariably influence the popularity of your resource, because even with the best content in the world, a slow site will irritate readers and sooner or later you will lose them. In this article we will optimize the most popular blogging engine - Wordpress, running on PHP. At the same time, let’s look at a few general points in website optimization.
1 Testing the current speed
To find out if anything has changed after our optimization, it doesn’t hurt to first measure the current loading speed of your blog pages, so that you have something to compare with. There are several tools that will help you do this:Don't forget to update to the latest version of PHP and Apache.
3.1 Disable unused services
You can get more available RAM by disabling unused services and optimizing MySQL and Apache.- Remove ClamD;
- Configure SpamD to use only 1 child process;
- Uninstall Mailman, unless, of course, you intend to run an email service.
3.2 MYSQL Query Cache
Since the stability and speed of Wordpress depends quite heavily on the operation of the database, it is worth making sure that the settings are in my.cnf correspond to the server's capabilities. First of all, you should set the request caching settings by adding my.cnf the following lines:query_cache_type = 1
query_cache_limit = 2M
query_cache_size = 20M
For the settings to take effect, you will have to restart the MySQL service.
3.3 Compiler cache: XCache or Eaccelerator?
The compiler cache increases the performance of compiled scripts on the server by caching them - this will help reduce the execution time of PHP scripts. It's worth trying both solutions, but according to experimental results, the performance increase when using Xcache is 5% higher than with Eaccelerator.3.4 Increase the maximum number of connections on Apache
Increasing the maximum number of connections in httpd.conf will increase productivity, because the server will be able to handle more connections at a time. However, you should change this setting carefully so as not to exhaust the entire amount of RAM and slow down the server, so always test new settings before putting them into operation. Let’s establish, for example, 150 connections:max_connections = 150
Don't forget to restart the Apache service to apply the settings.
4 Code and graphics optimization
So, the server is up and running and now it’s time to play with the Wordpress code.4.1 Disable hotlinks
Every time you use your server to store images, you are using significantly more of its resources. Quite often, people borrow your images by hotlinking them on their servers. This not only takes up the channel, but also creates a certain load on the server.Add the following code to .htaccess file, replacing example.com to your domain name to disable the use of hotlinks:
< IfModule mod_rewrite .c >
RewriteEngine on
RewriteCond %(HTTP_REFERER) !^$
RewriteCond %(HTTP_REFERER) !^http://(www\.)?example\.com/.*$
RewriteRule .*\.(gif|jpg|png|ico)$ -
ifModule >
4.2 Use external hosting to store images
Hosting images on external servers will help significantly reduce the load on the server. In the example below, you can see a decrease in the amount of RAM used on one of the blogs after moving images to Amazon S3.4.3 Compress java script code
Compressing javascript is a fairly simple task. Since it runs on every page view, you can reduce the size of the Javascript by removing all white space. Here's a simple tool that can do this for you - JavaScript Compressor.4.4 Javascript at the top of the page
It often happens that the site starts to load slowly or stops altogether, because... another resource from which javascript is called (for example, Digg badges, Tweetmeme, etc.) is not available or is offline. To avoid this, place all the javascript code at the end of the page, and what could not be included for some reason, try enclosing it in an iFrame.4.5 Use your browser cache
The browser cache itself, of course, will not make your blog faster, but it will help reduce the load on the server by caching frequently loaded objects (styles, interface elements, etc.).Try pasting the following code into .htaccess file:
FileETag MTime Size
< ifmodule mod_expires .c >
< filesmatch "\.(jpg|gif|png|css|js)$" >
ExpiresActive on
ExpiresDefault "access plus 1 year"
filesmatch >
ifmodule >
4.6 Compress static data
You can reduce the page load size by allowing the browser to receive and transmit data in compressed form. This will also reduce channel load and the amount of data downloaded.The following code in .htaccess can help you with this:
AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml application/xhtml+xml text/javascript text/css application/x-javascript
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4.0 no-gzip
BrowserMatch bMSIE !no-gzip !gzip-only-text/html
4.7 Use CDN for static files
If you store all the images on the same domain, the browser will wait for them to load one after the other. Let’s say you have 12 of them on the page, if you divide them between three subdomains, they will be loaded simultaneously from three “different” sources instead of being loaded by the browser one by one.You can try moving all css & javascript files to files.yoursite.com, and images and temporary files on static.yoursite.com. Or simply use CDN (Content Delivery Network) - a large network of servers located around the world, which will allow you not only to store your files on different subdomains, which means download them in parallel, but also to deliver data to the user from the server closest to him. All this will allow you to load data much faster.
5 Wordpress
In this part of the article, we will look at performance improvement techniques that can be applied directly to Wordpress.5.1 Update to the latest version
Updating to newer versions not only fixes detected vulnerabilities, but also improves performance. For example, in WordPress 2.8 the work with the database has been significantly optimized.5.2 Disable Post Revisions
In all versions of WordPress, starting from 2.6, revisions of your articles were automatically saved every time you edited them. This slows down the database and increases its size unnecessarily.To disable post revisions, add the following line to wp-config.php :
define("WP_POST_REVISIONS", false);
To delete previously saved text revisions, run the following query in PHPmyadmin:
DELETE a,b,c
FROM wp_posts a
LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id)
LEFT JOIN wp_postmeta c ON (a.ID = c.post_id)
WHERE a.post_type = "revision"
5.3 Reduce the number of requests
Remove unnecessary queries to speed up page generation. For example, the following is a typical code found in all WordPress themes:< meta http-equiv ="Content-Type" content ="< ?php bloginfo ("html_type" ); ?>; charset= php bloginfo ("charset" ); ?> " />
We can easily rewrite it in:
< meta http-equiv ="Content-Type" content ="text/html; charset=UTF-8" />
Already two fewer requests. Pretty simple, isn't it?
6 Wordpress Plugins
And finally, I bring to your attention several plugins that can improve WordPress performance. Once everything described above is completed, these plugins will help you achieve even better performance.Wordpress in the standard installation is quite slow. By default, the engine does not use some of the features of the modern Web to significantly speed up its performance. There are a whole bunch of plugins for optimizing Wordpress. Let's put them in order and carry out a major optimization.
Before we get started, let's see what a bare WordPress installation shows by Pagespeed:
A score of 76 out of 100 is quite low. Let's see how much we can increase this figure.
Server part
Nginx
If you're not using Nginx yet, it's time to switch to it. A simple and powerful solution. Configuration for working with permalinks support and static caching:Server ( server_name wp.com; root /var/www/wp; # path to WP index index.php; location ~* ^.+\.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf |rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ ( access_log off; log_not_found off; expires max; # static caching ) location / ( try_files $uri $uri/ /index.php?$args; # permalinks ) location ~ \.php$ ( fastcgi_pass unix:/var/run/php5-fpm.sock ; fastcgi_index index.php; include fastcgi_params;
PHP cache
Unless you have some special reason why you cannot install APC, be sure to enable it. We check for the presence of APC (in response we will receive a list of APC settings):Php -i | grep apc
PHP versions after 5.5 have a built-in opCache module, so you don't have to install APC.
Mysql tuning
Wordpress uses InnoDB, which means we can significantly increase MySQL performance by adjusting a number of parameters (my.cnf file) to our hardware:It is better to set the InnoDB buffer size to half the available RAM:
Innodb_buffer_pool_size = 256M
Don't forget to enable MySQL caching:
Query_cache_size = 32M query_cache_limit = 1M
More advanced MySQL setup for Wordpress.
Caching
This is the most important point. Caching can significantly speed up your site and save server resources. For clarity, we will use ab from Apache. Let's check the standard installation of Wordpress without caching. We send requests through the local network, so nothing but Wordpress itself creates a delay:Ab -c 10 -n 500 http://wordpress/
We get an average time per request of about 50ms:
Total transferred: 4183000 bytes HTML transferred: 4074500 bytes Requests per second: 17.62 [#/sec] (mean) Time per request: 567.421 (mean) Time per request: 56.742 (mean, across all concurrent requests) Transfer rate: 143.98 received
Chrome shows an average response wait of 150ms (server located in the Netherlands):
WP Super Cache
This plugin allows you to enable caching literally in one action. In addition to standard settings, it contains a large number of parameters for tuning the cache. Download the plugin, activate it in the control panel and enable the cache:With WP Super Cache enabled, we reduce the average time per request by 25 times(!):
Total transferred: 4293500 bytes HTML transferred: 4146500 bytes Requests per second: 499.01 [#/sec] (mean) Time per request: 20.040 (mean) Time per request: 2.004 (mean, across all concurrent requests) Transfer rate: 4184.61 received
The average wait for a response in Chrome has decreased by 3 times:
As a server-side alternative to WP Super Cache, you can use Varnish. It allows you to reduce the time for processing a request by almost an order of magnitude, but the solution itself is less flexible (well suited for blogs without dynamic elements).
Styles, scripts and pictures
Minification and compression
Minifying CSS/JS can save 10...15% of their size. To enable static minification there is a WP Minify module. Download, activate and the module will start working. Gzip will reduce the size of text files several times. In Nginx"e it is enabled like this:Server ( ... gzip on; gzip_disable "msie6"; gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript; ... )
Image optimization
Pictures can make up a very large portion of the overall page size. Lossless image compression can save 30...40% of their size. The EWWW Image Optimizer module can do this. For it to work you will need to install imagemagick and the gd library:Apt-get install imagemagick php5-gd
Good practices and experience
- It is best to choose VPS for Wordpress hosting. On Shared hosting, much of what is described above cannot be done. In addition, VPS is now quite cheap.
- Test themes with Pagespeed before use
- Empty the trash
- Delete old post revisions
- Delete spam comments
- Turn off trackbacks when things get really slow
- Share RSS via feedburner
As a result
We were able to speed up a bare Wordpress installation by almost 100 times in page generation time (we enabled Varnish) and increase the Pagespeed score from 76 to 93:I present the most complete instructions with ways to speed up a website on WordPress. Using the methods described below, I speeded up the loading time of my site from 24.40 seconds to 1.41 seconds. Increased download speed by 17.3 times! Good result. To find out how, read the full article.
I measured the speed of the site using the Pingdom Speed Test service. Tested the main page of the site. See below the site indicators “before” and “after” improvements, and short and complete instructions for speeding up the site.
Website loading speed indicators
Screenshot of speed measurement BEFORE optimization blog:
Screenshot of speed measurement after optimization and the recommendations below.
.
A short summary on speeding up a WordPress site
The main influence on the speed was made by such factors as changing hosting using SSD drives, optimizing images, enabling the W3 Total Cache caching plugin, optimizing the site database, deleting old revisions, enabling file compression on the server side, enabling a cache for static files on the browser side. What follows is a complete, detailed guide to speeding up a WordPress site.
Complete instructions on how to speed up a WordPress site
1. High-quality SSD hosting, fast ping
Hosting must be on SSD drives. It is advisable that the hosting servers be located in your geographic area to which the site is targeted. If the hosting is on an SSD, but in the USA, and your blog is focused on Russia and the CIS countries, then such an SSD will be of little use. Since there will be a long ping to communicate with the server. Therefore, the location of the hosting data center is also important. This is an important hosting parameter - fast ping, server response. And so that the hoster does not oversell services. About the type of hosting - of course it’s better to take a VDS (virtual dedicated server) with the parameters necessary for your site, instead of regular shared hosting. Which VDS configuration to choose depends on the load that your website creates not on the server and on the size of its daily audience. I would advise taking at least 1Gb Ram, 1 processor core and 10 GB SSD. At the beginning I had VDS on regular HDD drives, then I changed it to SSD VDS hosting.
Hosting "Before":
By prohibiting site indexing in this way, you can reduce the load on the hosting, and therefore speed up the loading of the site, freeing up server resources.
5. Setting up the .htaccess file to reduce the load on the server.
In the .htaccess file, additional commands for hosting are specified. Using special settings, you can remove unnecessary load on the server and speed up the site.
Setting No. 1. Often information is copied from websites along with pictures without changing the addresses of the pictures. And when this happens, images located on our hosting are loaded on other sites, and this creates an unnecessary load on the hosting.
The following code can prevent images from loading on our site on third-party sites:
RewriteEngine On RewriteCond %(HTTP_REFERER) !^http://(.+.)?yandex.ru/.*$ RewriteCond %(HTTP_REFERER) !^http://(.+.)?undsoft.com/.*$ RewriteCond %(HTTP_REFERER) !^http://(.+.)?yandex.net/.*$ RewriteCond %(HTTP_REFERER) !^http://(.+.)?feedburner.com/.*$ RewriteCond % (HTTP_REFERER) !^http://(.+.)?mail.ru/.*$ RewriteCond %(HTTP_REFERER) !^http://(.+.)?poisk.ru/.*$ RewriteCond %(HTTP_REFERER ) !^http://(.+.)?yourdomain.ru/.*$ RewriteCond %(HTTP_REFERER) !^$ RewriteRule .*.(jpe?g|gif|bmp|png)$ - [F]
After adding this code, an error will appear on someone else's site instead of your image.
Setting No. 2. In the .htaccess file, you can and should specify caching for some site objects (images, css and js files) so that the browser caches them on its side and does not download them every time. To do this, add the following code to .htaccess below the first code:
FileETag MTime Size
Setting No. 3. Let's enable gzip compression of pages before sending them to the user. Let's insert the following code into .htaccess:
Setting No. 4. Limit spam in comments. Most spam comments are sent automatically. With this code we will prohibit directly sending comments bypassing the comment form. Now spam bots will not be able to send comments.
RewriteEngine On RewriteCond %(REQUEST_METHOD) POST RewriteCond %(REQUEST_URI) .wp-comments-post.php* RewriteCond %(HTTP_REFERER) !.*yourdomain.ru.* RewriteCond %(HTTP_USER_AGENT) ^$ RewriteRule (.*) ^http: //%(REMOTE_ADDR)/$
Setting No. 5. If you use the FeedBurner system, then you obviously have plugins installed that send RSS content to the FeedBurner site. Today you can remove them, because you can redirect content without plugins, reducing the load on your hosting.
RewriteEngine on RewriteCond %(HTTP_USER_AGENT) !FeedBurner RewriteCond %(HTTP_USER_AGENT) !FeedValidator RewriteRule ^feed/?([_0-9a-z-]+)?/?$ http://yourdomain.ru
ATTENTION!!! In the examples above, do not forget to replace the address yourdomain.ru with the address of your website.
6. Database optimization
The Database is important in the speed of the site. When saving posts several times, WordPress creates post revisions - the states of posts at different points in their editing. As a result, over time, the database contains a large number of unnecessary post revisions, and these need to be cleaned and optimized. This can be done using Optimize DB plugin. You can install it from the WordPress admin area. For example, when I launched it on my website, I deleted more than 1,200 post revisions. This significantly improved the speed of the database.
7. Template (theme) code optimization
Optimizing the theme code involves removing unnecessary queries and/or replacing them with specific values, such as the blog title.
Setting No. 1. Find the code that is responsible for styles in the header.php file:
" type="text/css" media="screen" />
Replaced by:
Attention!!! Don't forget to change yoursite.ru to the link of your site.
Setting No. 2. Change pinback code:
" />
Setting No. 3. Changing the RSS feed code:
RSS Feed" href="" />
Correctly replace yoursite.ru with your link:
Setting No. 4. Quite often, in the footer of the site (footer.php), theme developers leave completely unnecessary queries to the Database. For example:
This code simply displays the name of the site, so as not to have to access the database again, it’s wiser to write the name yourself once and not load the site. You can search for the same code in other sections of the site, but think before deleting it.
1) If your site does not use comments, you should not hide them using plugins, this creates a completely unnecessary burden. Since you don't need comments at all, just remove the following code from your theme file (single.php):
2) Try not to use external scripts, such as comments from VKontakte, various social network widgets. Yes, it looks beautiful and impressive, but it creates a decent load on the site. From the examples, I can say that my site significantly loaded the web viewer code from YandexMetrica, the Add.This widget. I changed the social media buttons to a hotel JS plugin.
3) Clean all the code of your site from comments, these comments are inserted using tagsand /*code/. Leave only what you need, since the site has to spend extra effort loading them...
4) Try to place all scripts at the end of the page before the closing tag