How to Serve Images from a Sub-Domain in WordPress

How to Serve Images from a Sub-Domain in WordPress

We all know that loading of a website matters a lot for great user-experience, and for search engine ranking. For speed up loading time for your website there are CDN networks available in market likeMaxCDN, Cloudflare etc. Serving images from sub-domain also improves loading time because of the parallel downloading ability of a browser. Many high traffic websites are using CDN or sub-domain to divide the load from main domain.

Here I will show you how to serve images from a sub-domain and also redirect the older ones to the new ones.

Create a Sub-Domain

Log in to your Web Hosts C panel, look for Subdomains 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.

Set-up a Sub-Domain in WordPress

In early WordPress version it was easy. Go to Settings -> Media and enter the sub-domain in Full URL Path to files. For set-up sub domain in latest WordPress version just go to http://www.yoursite.com/wp-admin/options.php and update the values of upload_path and upload_url_path.

Enter the sub-domain in the upload_url_path to files with http in the beginning and no trailing slash (/) in the end. Then click on Save Changes.

Now you have set up sub domain for WordPress images upload but the older posts still use the complete URL. It can be change using the SQL Query.

For that you have to open phpMyAdmin from the Web Host cPanel. Then click on SQL from the top navigation bar and enter the query given below and click on Go.

UPDATE wp_posts SET post_content = REPLACE(post_content,'http://www.yoursite.com/wp-content/uploads/','http://img.yoursite.com/')

Make sure to replace yoursite.com with your actual domain.

It is good to add this sub domain immediately after installing WordPress website. But those who are new to WordPress don’t think of this kind of development. So, if you have number of posts with images in your website, you have to redirect the previous URL’s (i.e. http://www.yoursite.com/wp-content/uploads/image.jpg) to the new sub-domain URL’s. Otherwise search engine treats your image url as a duplicate one. All you have to do is enter the following code in the .htaccess file and save it.

RedirectMatch 301 ^/wp-content/uploads/(.*)$ http://img.yoursite.com/$1

Make sure to replace yoursite.com with your actual domain.

1 I like it
0 I don't like it

Leave a Reply

Your email address will not be published. Required fields are marked *