All Products
Search
Document Center

Object Storage Service:Configure a CDN-accelerated domain name in an OSS SDK

Last Updated:Jun 16, 2026

When you use Object Storage Service (OSS) with Alibaba Cloud CDN, outbound traffic and origin traffic fees apply. To offset these fees with a back-to-origin traffic package in an OSS SDK, replace the bucket domain name with your custom domain name configured for CDN acceleration and specify the CNAME during SDK initialization.

The following examples show how to configure CDN acceleration in different SDK languages.

Important

Ensure the `OSS_ACCESS_KEY_ID` and `OSS_ACCESS_KEY_SECRET` environment variables are set, and specify your custom domain name configured for CDN acceleration, such as `example.com`.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
public class Demo {
    public static void main(String[] args) throws Exception {
        // Specify the custom domain name that is configured for CDN acceleration, such as example.com.
        String endpoint = "http://example.com";
        // Specify the region that corresponds to the Endpoint, such as cn-hangzhou.
        String region = "cn-hangzhou";
        // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
              
        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // Explicitly declare the use of the V4 signature algorithm.
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        // Enable CNAME. CNAME is used to map a custom domain name to the destination bucket.
        clientBuilderConfiguration.setSupportCname(true);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();
        try {
            // Create a ClientConfiguration instance. You can modify the default parameters as needed.
            ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
            // Enable CNAME. CNAME is used to map a custom domain name to the destination bucket.
            conf.setSupportCname(true);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\OssClient;
use OSS\Core\OssException;

// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$accessKeyId = getenv("OSS_ACCESS_KEY_ID");
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// Specify the custom domain name that is configured for CDN acceleration, such as example.com.
$endpoint = "https://example.com";

try {
    // Enable CNAME. CNAME is used to map a custom domain name to the destination bucket.
    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, true);
} catch (OssException $e) {
    print $e->getMessage();
}                    
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())

# Specify the custom domain name that is configured for CDN acceleration, such as example.com.
cname = 'http://example.com'

# Set is_cname to True to enable CNAME. CNAME is used to map a custom domain name to the destination bucket.
bucket = oss2.Bucket(auth, cname, 'examplebucket', is_cname=True)                   
using Aliyun.OSS;
using Aliyun.OSS.Common;

// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the custom domain name that is configured for CDN acceleration, such as example.com.
const string endpoint = "https://example.com";

// Create a ClientConfiguration instance. Modify the default parameters as needed.
var conf = new ClientConfiguration();
// Enable CNAME. CNAME is used to map a custom domain name to the destination bucket.
conf.IsCname = true;

// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);                    
package main

import (
    "fmt"
    "os"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
    // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Create an OSSClient instance.
    // Specify the custom domain name that is configured for CDN acceleration, such as example.com.
    client, err := oss.New("https://example.com", "", "", oss.UseCname(true), oss.SetCredentialsProvider(&provider))
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
}
#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the custom domain name that is configured for CDN acceleration, such as example.com. */
const char *endpoint = "https://example.com";

void init_options(oss_request_options_t *options) {
    options->config = oss_config_create(options->pool);
    /* Initialize the aos_string_t type with a char* string. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */    
    aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
    aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
    /* Enable CNAME. CNAME is used to map a custom domain name to the destination bucket. */
    options->config->is_cname = 1;
    options->ctl = aos_http_controller_create(options->pool, 0);
}
int main() {
    aos_pool_t *p;
    oss_request_options_t *options;
    /* Initialize global variables. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        return -1;
    }
    /* Initialize the memory pool and options. */
    aos_pool_create(&p, NULL);
    options = oss_request_options_create(p);
    init_options(options); 
    /* Release the memory pool. This releases the memory allocated for resources during the request. */
    aos_pool_destroy(p);
    /* Release the previously allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}