All Products
Search
Document Center

Object Storage Service:How do I configure an accelerated domain name for CDN by using OSS SDKs?

Last Updated:Oct 10, 2023

When you use Object Storage Service (OSS) together with CDN, you are charged outbound traffic fees and origin traffic fees by CDN. If you want to use back-to-origin traffic plans to offset fees when you use OSS SDKs, you must replace the bucket domain name with the custom domain name that you configured for Alibaba Cloud CDN and add a CNAME record when you initialize OSS SDKs.

The following code provides examples on how to configure an accelerated domain name for CDN by using OSS SDKs in multiple programming languages:

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.model.*;
public class Demo {
    public static void main(String[] args) throws Exception {
        // Enter the custom domain name that you configured for Alibaba Cloud CDN. Example: example.com. 
        String endpoint = "http://example.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
              
        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        try {
            // Create a ClientConfiguration instance and modify the default parameters based on your business requirements. 
            ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
            // Enable CNAME. CNAME is used to map the custom domain name to the 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 the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
$accessKeyId = getenv("OSS_ACCESS_KEY_ID");
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// Enter the custom domain name that you configured for Alibaba Cloud CDN. Example: example.com. 
$endpoint = "https://example.com";

try {
    // Enable CNAME. CNAME is used to map the custom domain name to the 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 the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())

# Enter the custom domain name that you configured for Alibaba Cloud CDN. Example: example.com. 
cname = 'http://example.com'

# Enable CNAME and use CNAME to map the custom domain name to the 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 the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Enter the custom domain name that you configured for Alibaba Cloud CDN. Example: example.com. 
const string endpoint = "https://example.com";

// Create a ClientConfiguration instance and modify the default parameters based on your business requirements. 
var conf = new ClientConfiguration();
// Enable CNAME. CNAME is used to map the custom domain name to the 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 the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Create an OSSClient instance. 
    // Enter the custom domain name that you configured for Alibaba Cloud CDN. Example: 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"
/* Enter the custom domain name that you configured for Alibaba Cloud CDN. Example: example.com. */
const char *endpoint = "https://example.com";

void init_options(oss_request_options_t *options) {
    options->config = oss_config_create(options->pool);
    /* Use a char* string to initialize data of the aos_string_t type. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */    
    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 the custom domain name to the 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 operation releases the memory resources allocated for the request. */
    aos_pool_destroy(p);
    /* Release the allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}