[WordPress] How to Serve Images from Subdomain | Steps to Host Images on Sub-domain

The number of parallel connections a web browser can open to fetch the contents from a web server is limited (about 6-12). So, if there are 120 contents that need to be fetched from your web server, there will 10-20 roundtrips. As the number of roundtrips increases, the page speed slows down. We all know that page speed is one of the major criteria for better search ranking. If a webpage takes more than 4 seconds to open, there is a possibility of losing a large number of visitors. So, the webmasters must try to minimize the roundtrips. If you create a subdomain to deliver the image files of your blog, the number of parallel connections will increases (6-12 connections for the main domain and 6-12 connections for subdomain). This way the number of roundtrips will also decrease. 

In the post, I am going to show how you can serve images from a subdomain instead of the main domain. Here are the steps:

  1. Create a subdomain: Log into the control panel of your website and add a subdomain. The document root should be “public_html/wp-content/uploads“. If you have installed WordPress in a folder, the document root will be “public_html/folder-name/wp-content/uploads“.How to Serve Images from Subdomain
  2. Change Media Settings: Log into your WordPress using admin credentials. Go to Settings and click on Media. If you do not see “Full URL path to files” there, you need to update “upload_url_path” in the Options table.
    • Access your database and update the value of the field “upload_url_path” in the Options table with your subdomain name (e.g. https://img.example.com). Now the Media will show “Full URL path to files” and “Store uploads in this folder“. Keep “Store uploads in this folder” empty. “Full URL path to files” will have your subdomain name.upload_url_path
    • Click on “Save Changes”.
  3. Update the current image path: In the Posts table, post_content column stores the path to the image file as a part of its values. You need to run a query to change that path. Run the following SQL to change the path to the existing images.

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

4. Redirect old image path to a new path: You do not want to keep the duplicate contents. So, you need to make some changes in your .htaccess file so that search engines can update the location of your old images. Open your .htaccess file and add the following lines.

RewriteEngine On
RedirectMatch 301 ^/wp-content/uploads/(.*)$ https://img.example.com.com/$1

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.