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
- Register on the Qiniu Cloud website and create a storage bucket.
- Obtain the CDN domain (the
$qiniu_hostin the code) for that bucket. - Copy the code to the end of your theme's
functions.phpfile. - Modify the
$local_hostand$qiniu_hostvariables with your actual domains. - After saving, image links in the
wp-contentandwp-includesdirectories 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.