Blog / WordPress/ Accelerate Your WordPress Site with Qiniu Cloud Storage via Code

Accelerate Your WordPress Site with Qiniu Cloud Storage via Code

WordPress代码实现七牛云存储加速博客网站

Introduction to Qiniu Cloud Storage

Qiniu Cloud Storage (Object Storage Service) specializes in storing and delivering static website resources like CSS, JavaScript, and image files. Hosting these resources on Qiniu's CDN can effectively reduce server load and significantly improve user access speed.

For personal blogs or small websites, Qiniu offers new users 10GB of free storage and 10GB of free monthly traffic, which is generally sufficient. This guide explains a code-only implementation method that requires no plugins.

Code Implementation

Add the following code to the end of your current WordPress theme's functions.php file, modifying the domain variables according to your setup.

// Qiniu Cloud Storage Acceleration
if (!is_admin()) {
    add_action('wp_loaded', 'c7sky_ob_start');
    function c7sky_ob_start() {
        ob_start('c7sky_qiniu_cdn_replace');
    }
    function c7sky_qiniu_cdn_replace($html) {
        $local_host = 'https://www.yoursite.com'; // Your website domain
        $qiniu_host = 'https://img.yourcdn.com'; // Qiniu CDN domain
        $cdn_exts   = 'png|jpg|jpeg|gif'; // File extensions to accelerate
        $cdn_dirs   = 'wp-content|wp-includes'; // Directories to accelerate
        if ($cdn_dirs) {
            $regex = '/' . preg_quote($local_host, '/') . '/((' . $cdn_dirs . ')/[^s?'"&;>]*.(' . $cdn_exts . '))(['"s?])/';
            $html = preg_replace($regex, $qiniu_host . '/$1$4', $html);
        } else {
            $regex = '/' . preg_quote($local_host, '/') . '/([^s?'"&;>]*.(' . $cdn_exts . '))(['"s?])/';
            $html = preg_replace($regex, $qiniu_host . '/$1$3', $html);
        }
        return $html;
    }
}

Configuration and Usage Steps

  1. Register on the Qiniu Cloud website and create a storage bucket.
  2. Obtain the CDN domain (the $qiniu_host in the code) for that bucket.
  3. Copy the code to the end of your theme's functions.php file.
  4. Modify the $local_host and $qiniu_host variables with your actual domains.
  5. After saving, image links in the wp-content and wp-includes directories will automatically be replaced with Qiniu CDN links.

Note: This method uses output buffering for HTML link replacement, which may have a slight performance impact. For high-traffic sites or performance-critical scenarios, consider more efficient caching solutions or the official plugin.