We all know that Google started ranking website based on Page speed. Though the difference due to page speed could be as low as 1%, but it’s one of the part of Google SEO suggestion. In this post I’m going to share how you can host images in a sub-domain and server images to main blog.
Earlier I shared how to use dropbox as CDN, but using Dropbox was a little manual so I wanted something automatic which may also improve my site speed. After searching the web, I found that serving images from a sub-domain also improves the loading time because of the parallel downloading ability of a browser. In this post I will tell you how to serve images from a sub-domain and also redirect the older ones to the new ones.
October 2016 update: You should use MaxCDN or KeyCDN for serving images from CDN under your website sub-domain.
Creating A Sub-domain
Log in to your web-hosts CPanel, scroll down and look for sub-domains under domains and click on it.
Enter a name for the sub-domain i.e img.example.com, give the path of the uploads folder which is usually public_html/wp-content/uploads and click on create.
Setting a Sub-Domain in WordPress
Using a sub-domain is really easy. Go to Settings >> Media and enter the sub-domain in the Full URL path to files with http in the beginning and no trailing slash (/) in the end. Click on save changes. Look the image for more clarification.
You have set up sub domain for WordPress images but the older posts still use the complete URL. They can be changed to the sub-domain using the following SQL query. First open phpMyAdmin.
Click on SQL from the nav-bar and enter the query given below, then click on Go. Make sure to replace example.com with your actual domain.
UPDATE wp_posts SET post_content = REPLACE(post_content,'http://www.example.com/wp-content/uploads/'
Redirecting Old Images to the new one
Other pages on the Web and Search engines might have indexed your images so it is better to redirect them to the new images which are hosted on sub-domain. All you have to do is enter the following code in the .htaccess file and save it. If .htaccess file isn’t available then create one.
RedirectMatch 301 ^/wp-content/uploads/(.*)$ http://img.example.com/$1
Make sure to replace example.com with your actual domain.
I hope this tutorial helped you in improving you page speed. Do check your website’s speed using these tools and tell us about your new load time.