Optimizing your infrastructure to make WordPress run snappier!

WordPress is an easy platform with its benefits. As I have seen many requests on how to speed up a website, I have made a list of points that you should look into. This information can be very effective as without taking any tuning, you could end up with a website that even a sloth can beat if it would be a race against time.
To prevent your site from becoming slow, these are some things you should always keep behind your head.

But first, why would your site’s speed matters?
When a person lands on your site for the first time, you only have a few seconds to capture their attention to convince them to hang around or they will leave.
According to a report by the Microsoft team, a two-second delay already could damage the satisfaction of your customers. The loss of revenue on platforms such as Google AdSense could be lowered by 4.3% in just a day.
Not only that, but Google now includes the site’s speed in it’s ranking algorithm!
This means that your site’s speed effects SEO, so if your site is slow, you’re now losing potential visitors and reduced rankings in search engines.

These tips and tricks are the ones I use to keep a partner site of mine called DevineHQ nice and speedy.
Please note that some of the stuff might be outdated by the time you read it, or that it might not be optimal for your specific situation.
But without any further ado, let’s dive into it!


Shared hosting vs. VPS – which is right for you?

First of all, let’s get down what the difference between Shared hosting and VPS is.

Shared hosting means that more people using the same server as you do, Massively reducing the cost so everyone can create their website. However, if one user would let the server crash, your website will be affected as well.
This is somewhat rare, but not unheard of.
Shared hosting also does have its limits. For example, if your provider doesn’t run the latest versions of software like PHP, you’ll be at their mercy.
While this is uncommon, but might be the case with some budget providers.

A VPS server is your own virtualised server in the cloud.
With a VPS, you have near full of the software that you are using.
A VPS server is a better (though more costly) alternative to shared hosting if you know what you are doing.
They are generally a lot faster and others won’t hog your precious resources.
Of course, if you don’t know what you’re doing, having so much control might become more of a burden instead.
Not only can it decrease the performance of your site, it can also potentially create security issues.
To make the use of a VPS easier, make sure you use “Plesk”. This software can be perfect for running multiple WordPress installations or websites in general on your VPS. More information of that can be found here.


PHP7 – Harder, Better, Faster, Stronger

A big factor in making your site faster can actually be something as simple as updating your server software.
PHP is one of these packages.
In December of 2015, The PHP Group released PHP7.
With that, a lot of new features and optimizations came into play.
Not only did it get a new upgraded engine (the “PHP Next Generation Engine”, based on the “Zend Engine”), it also cleaned up (removed) some old functions that nobody should be using any more anyway.
While this might break some sites, WordPress had barely any issues with it as they keep WordPress updated for the latest PHP versions.
It is pretty much a must to update to the latest PHP version if you want to have a snappy site.


Opcache – Less compiling, more serving!

Did you know there is another simple way to speed up your site with very little effort?
Yes, we’re talking about Opcache.

You see, when PHP code runs, it compiles everything into an opcode (operation code).
This opcode contains all the instructions which can then be parsed and executed by the PHP engine.
Without Opcache, this process of compiling, parsing and executing happens every time a request is being processed.
This wastes huge amounts of resources and this waste increases exponentially with the number of visitors your site gets!

With Opcache, the compiling step is taken out of the equation.
When enabled, it scans the file and if there is an Opcode available in the Opcache it will fetch, parse and execute that instead.
If there is no cached version available, it will compile it instead.
This way, only the first person or two to visit the site since the cache expiry might be affected by this speed loss, but in the end, it will save a lot of time and resources!

A downside to Opcache is when you’re editing the script, changes might not appear until the cache expires.
In development, Opcache should thus be disabled until you get into production.


Image optimization

We know that Yahoo is having an option to reduce images and keeping the perfect quality. However, every time doing this makes your head go spinning around to save memory on your theme so everything loads as fast as possible.

Here are several plugins that you can make use of to optimize images.
Smush
WP Image Lazy Load
Imagify

Note for more experienced users: Make sure you have Gzip compression activated on your server. If not, activate it and restart your server. The effect will blast you from the chair.
Disclaimer: I use my own custom scripts to optimize images on my site.


CDN Networks – Spend fewer resources on static content

A proper CDN (Content Delivery Network) is a great option when it comes to serving static content like images.

Most websites are making use of a CDN.
Essentially, a CDN takes all the static files you’ve got on your site (CSS, Javascript and images etc.) and lets visitors download them as fast as possible by serving the files on servers as close to them as possible.
There are a lot of CDN options available, both paid and free.
Cloudflare is a great CDN that also protects your website from some well-known (D)DoS attacks (if setup properly).
And the best about Cloudflare? its basic functionality is completely free!
You can decide to upgrade for some extra features, but those are optional.

Some other well-known CDN’s that you might take a look at include but are not limited to:
CacheFly
Incapsula
MetaCDN


Disable hotlinking – Don’t let them steal your bandwidth!

Hotlinking is a form of bandwidth “theft.” It occurs when other sites direct link to the content on your site (eg. images) making your server do the heavy lifting
This can add up as more and more sites hotlink your content.
Depending on what web server software you use (eg. Apache or Nginx) you can add the following pieces of code to your config.

For Apache, place this in the .htaccess in your root:

# Disable hotlinking of images with forbidden or custom image option
RewriteEngine on													 # Enable the rewrite engine
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC] # Allow yourdomain.com
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?google.com [NC] 	# Allow google.com
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?bing.com [NC]	   # Allow bing.com
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yahoo.com [NC]	  # Allow yahoo.com
RewriteRule \.(jpg|jpeg|png|gif|svg)$ – [NC,F,L]	                 # Give a 403 forbidden to anyone else

For Nginx, please this in your site’s config file:

location ~ .(gif|png|jpeg|jpg|svg)$ {
     valid_referers none blocked yourdomain.com *.yourdomain.com ~.google. ~.bing. ~.yahoo.;
     if ($invalid_referer) {
        return   403;
    }
}

Setting expiry headers – Don’t make users waste bandwidth

Browsers keep fetched content in their cache for a small time so it doesn’t have to be fetched from the server.
For items that change rarely on your site, like your logo or favicon, you can set them to expire later.
For items that tend to change more often, you can shorten the time.
Generally speaking, you want to set the expire header on images: jpg, jpeg, gif, png, svg, javascript and css.
Just like with the hotlinking, you’ll have to add the following pieces of code to your .htaccess or site’s config file.

For Apache (required mod_expires):

<IfModule mod_expires.c>
	# Set expiry headers
    ExpiresActive On										  # Enable expiries
    ExpiresByType image/jpg "access plus 1 month" 			# Set expiry for image/jpg to 1 month
    ExpiresByType image/jpeg "access plus 1 month"		    # Set expiry for image/jpeg to 1 month
    ExpiresByType image/gif "access plus 1 month"			 # Set expiry for image/gif to 1 month
    ExpiresByType image/png "access plus 1 month"             # Set expiry for image/png to 1 month
    ExpiresByType text/css "access plus 1 month"              # Set expiry for text/css to 1 month
    ExpiresByType text/x-javascript "access plus 1 month"     # Set expiry for text/x-javascript to 1 month
    ExpiresByType image/x-icon "access plus 1 year"           # Set expiry for image/x-icon to 1 year
    ExpiresDefault "access plus 2 days"                       # Set expiry for anything else to two days
</IfModule>

For Nginx:

location ~* \.(?:css|js|gif|jpe?g|png)$ {
    expires 30d;
    add_header Pragma public;
    add_header Cache-Control "public";
}

location ~* \.(?:ico)$ {
	expires 1y;
    add_header Pragma public;
    add_header Cache-Control "public";
}

Note: You can use queries like ?version=1.0 to bypass caching immediately.
Every time you want to make the browser get a new version, change the query value.


Allowing bigger files – Save your visitors from a lot of headaches

Sometimes it happens that on accident (or purpose), a user wants to upload a bigger image to your server.
While this isn’t a big problem for some, it’s not something you or your server will like if the size is not limited.
By default, PHP limits the maximum file size to 2MB and the maximum post size to 8MB.
While this is fine for most purposes, sending bigger files to your site can be a hassle if it’s bigger than the aforementioned limits.
In order to change this, you will have to change something in your php.ini file.

Find the following lines:

upload_max_filesize = 2M
post_max_size = 8M

and replace them with the following lines respectively:

upload_max_filesize = 40M
post_max_size = 42M

Doing this allows you to upload images and other files without issues, while still somewhat limiting other data.

Note: 40MB can be a lot and this does open some opportunities for a (D)DoS. Please be cautious when using these values.


Optional stuff – Remove what is not needed

WordPress comes with some fun but useless stuff by default, this is called “bloat”.
While most of this is harmless, any bloat wastes resources and adds unneeded code which can be exploited by malicious users.
Remember: more code == more attack surface.

Take the default WordPress themes (Twenty Thirteen, Twenty Fourteen, Twenty Fifteen etc.) and Hello Dolly plugin for example.
While they are meant for starters, pretty much nobody uses them for a serious site.
You might as well just remove them and save yourself some precious resources.
This ties in with the “more code == more attack surface” mentality and also applies to any plugins you do no longer wish to use.

Some other stuff that can be changed include:

  • Show excerpts instead of full posts
    This can give them a little preview, without forcing them to scroll over the entire thing for the next post.
  • Reduce the number of posts on the page
    While this does make them have to click more, they won’t have to scroll to the bottom as much.
    Alternatively, one could use something called “[Infinite Scroll](https://wordpress.org/plugins/yith-infinite-scrolling/)” to not even have to click them for the next page!
  • Remove sharing widgets from pages
    Instead of having a “share now” button on every page, it is a lot sleeker to only have them in the posts, you know, where it actually matters?
    This prevents users from having to load some resources every single page where it doesn’t matter.
  • Keep it clean, keep it simple
    While it is great for your initial revenue to slap your site full of advertisements, in the long run, this might actually hurt your revenue.
    A visitor that returns daily will earn you more than a few people that will never return.
    People are here for your content, not to have to click away 600 advertisements.
    Keep your site’s main design as simple as possible as well.
    Animations are great, but it shouldn’t make your site sluggish.
    Neither should your site look like a site from the early-2000’s because you’ve crammed a truck-load of dildoes… I mean content, into as little space as possible.

Overal, keeping it simple and clean will make it more enjoyable (and do-able) for people to return to your site.


Final Words

Well, that’s about it for now.
I hope you guys could pick up something useful from this post 🙂
If you did, please share it around for others to read or consider sending me a donation 🙂

G33k Out!

Leave a reply