All Products
Search
Document Center

Object Storage Service:Map custom domain names (PHP SDK V2)

Last Updated:Aug 05, 2025

When objects are uploaded to an Object Storage Service (OSS) bucket, URLs are automatically generated for them. You can use these URLs, which are the public endpoints of the bucket, to access the objects. If you want to access these objects using custom domain names, you must add CNAME records to map the custom domain names to the bucket.

Precautions

  • If you want to access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For more information about the regions and endpoints that are supported by OSS, see Regions and endpoints.

Sample code

Create a CnameToken

The following code provides an example of how to create a CnameToken.

<?php

// Import the autoload file to load dependency libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define the descriptions for command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region is required. It specifies the region where the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint is optional. It specifies the domain name that other services can use to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name is required.
];

// Generate a list of long options to parse command-line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // A colon (:) is added after each parameter to indicate that a value is required.
}, array_keys($optsdesc));

// Parse the command-line arguments.
$options = getopt("", $longopts);

// Check whether required parameters are missing.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Prompt the user that a required parameter is missing.
        exit(1);
    }
}

// Obtain the values of the command-line arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.

// Load credentials, including the AccessKey ID and AccessKey secret, from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();

// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Set the region.
$cfg->setRegion($region);

// If an endpoint is provided, set the endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Create a request object to generate a CNAME token.
$request = new Oss\Models\CreateCnameTokenRequest(
    bucket: $bucket, // The bucket name.
    bucketCnameConfiguration: new Oss\Models\BucketCnameConfiguration(
        cname: new Oss\Models\Cname(
            domain: 'example.com' // The custom domain name.
        )
    )
);

// Call the createCnameToken method to generate a CNAME token.
$result = $client->createCnameToken($request);

// Print the result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code of the response.
    'request id:' . $result->requestId . PHP_EOL .   // The unique ID of the request.
    'cname token:' . var_export($result->cnameToken, true) . PHP_EOL // The generated CNAME token.
);

Obtain a CnameToken

The following code provides an example of how to obtain a CnameToken.

<?php

// Import the autoload file to load dependency libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define the descriptions for command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region is required. It specifies the region where the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint is optional. It specifies the domain name that other services can use to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name is required.
];

// Generate a list of long options to parse command-line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // A colon (:) is added after each parameter to indicate that a value is required.
}, array_keys($optsdesc));

// Parse the command-line arguments.
$options = getopt("", $longopts);

// Check whether required parameters are missing.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Prompt the user that a required parameter is missing.
        exit(1);
    }
}

// Obtain the values of the command-line arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.

// Load credentials, including the AccessKey ID and AccessKey secret, from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();

// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Set the region.
$cfg->setRegion($region);

// If an endpoint is provided, set the endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Create a request object to obtain a CNAME token.
$request = new Oss\Models\GetCnameTokenRequest(
    bucket: $bucket, // The bucket name.
    cname: 'example.com' // The custom domain name.
);

// Call the getCnameToken method to obtain the CNAME token.
$result = $client->getCnameToken($request);

// Print the result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code of the response.
    'request id:' . $result->requestId . PHP_EOL .   // The unique ID of the request.
    'cname token:' . var_export($result->cnameToken, true) . PHP_EOL // The obtained CNAME token.
);

Add a CNAME record

Map a custom domain name

<?php

// Import the autoload file to load dependency libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define the descriptions for command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region is required. It specifies the region where the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint is optional. It specifies the domain name that other services can use to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name is required.
];

// Generate a list of long options to parse command-line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // A colon (:) is added after each parameter to indicate that a value is required.
}, array_keys($optsdesc));

// Parse the command-line arguments.
$options = getopt("", $longopts);

// Check whether required parameters are missing.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Prompt the user that a required parameter is missing.
        exit(1);
    }
}

// Obtain the values of the command-line arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.

// Load credentials, including the AccessKey ID and AccessKey secret, from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();

// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Set the region.
$cfg->setRegion($region);

// If an endpoint is provided, set the endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSS client instance.
$client = new Oss\Client(config: $cfg);

// Create a request object to attach a custom domain name to the bucket.
$request = new Oss\Models\PutCnameRequest(
    bucket: $bucket, // The bucket name.
    bucketCnameConfiguration: new Oss\Models\BucketCnameConfiguration(
        cname: new Oss\Models\Cname(
            domain: 'example.com' // The custom domain name.
        )
    )
);

// Call the putCname method to attach the custom domain name to the bucket.
$result = $client->putCname($request);

// Print the result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code of the response.
    'request id:' . $result->requestId               // The unique ID of the request.
);

Map a custom domain name and attach a certificate

<?php

// Import the autoload file to load dependency libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define the descriptions for command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region is required. It specifies the region where the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint is optional. It specifies the domain name that other services can use to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name is required.
];

// Generate a list of long options to parse command-line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // A colon (:) is added after each parameter to indicate that a value is required.
}, array_keys($optsdesc));

// Parse the command-line arguments.
$options = getopt("", $longopts);

// Check whether required parameters are missing.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Prompt the user that a required parameter is missing.
        exit(1);
    }
}

// Obtain the values of the command-line arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.

// Load credentials, including the AccessKey ID and AccessKey secret, from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();

// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Set the region.
$cfg->setRegion($region);

// If an endpoint is provided, set the endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

$request = new Oss\Models\PutCnameRequest(
    bucket: $bucketName, // The bucket name.
    bucketCnameConfiguration: new Oss\Models\BucketCnameConfiguration(
        cname: new Oss\Models\Cname(
            domain: 'www.example.com', // Specify the custom domain name.
            certificateConfiguration: new Oss\Models\CertificateConfiguration(
                force: true, // Specifies whether to forcibly overwrite the certificate.
                certId: '92******-cn-hangzhou', // Specify the certificate ID.
                certificate: '-----BEGIN CERTIFICATE-----MIIFBzCCA++gT2H2hT6Wb3nwxjpLIfXmSVcV*****-----END CERT', // Specify the content of the certificate.
                privateKey: '-----BEGIN CERTIFICATE-----MIIFBzCCA++gT2H2hT6Wb3nwxjpLIfXmSVcV*****-----END CERTIFICATE-----' // Specify the content of the private key.
            )
        )
    )
);

// Call the putCname method to attach the custom domain name to the bucket.
$result = $client->putCname($request);

// Print the result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code of the response.
    'request id:' . $result->requestId               // The unique ID of the request.
);

Detach a certificate

If you no longer want to use a certificate for a domain name, you can detach the certificate.

<?php

// Import the autoload file to load dependency libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define the descriptions for command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region is required. It specifies the region where the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint is optional. It specifies the domain name that other services can use to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name is required.
];

// Generate a list of long options to parse command-line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // A colon (:) is added after each parameter to indicate that a value is required.
}, array_keys($optsdesc));

// Parse the command-line arguments.
$options = getopt("", $longopts);

// Check whether required parameters are missing.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Prompt the user that a required parameter is missing.
        exit(1);
    }
}

// Obtain the values of the command-line arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.

// Load credentials, including the AccessKey ID and AccessKey secret, from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();

// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Set the region.
$cfg->setRegion($region);

// If an endpoint is provided, set the endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create a request object to detach the certificate.
$request = new Oss\Models\PutCnameRequest(
    bucket: $bucketName, // The bucket name.
    bucketCnameConfiguration: new Oss\Models\BucketCnameConfiguration(
        cname: new Oss\Models\Cname(
            domain: 'www.example.com', // Specify the custom domain name.
            certificateConfiguration: new Oss\Models\CertificateConfiguration(
                deleteCertificate: true // Detach the certificate.
            )
        )
    )
);

// Call the putCname method to detach the certificate.
$result = $client->putCname($request);

// Print the result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code of the response.
    'request id:' . $result->requestId               // The unique ID of the request.
);

List CNAME records

The following code provides an example of how to list the CNAME records of a bucket.

<?php

// Import the autoload file to load dependency libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define the descriptions for command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region is required. It specifies the region where the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint is optional. It specifies the domain name that other services can use to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name is required.
];

// Generate a list of long options to parse command-line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // A colon (:) is added after each parameter to indicate that a value is required.
}, array_keys($optsdesc));

// Parse the command-line arguments.
$options = getopt("", $longopts);

// Check whether required parameters are missing.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Prompt the user that a required parameter is missing.
        exit(1);
    }
}

// Obtain the values of the command-line arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.

// Load credentials, including the AccessKey ID and AccessKey secret, from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();

// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Set the region.
$cfg->setRegion($region);

// If an endpoint is provided, set the endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Create a request object to list the custom domain names that are attached to the bucket.
$request = new Oss\Models\ListCnameRequest(
    bucket: $bucket // The bucket name.
);

// Call the listCname method to list the custom domain names that are attached to the bucket.
$result = $client->listCname($request);

// Print the result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code of the response.
    'request id:' . $result->requestId . PHP_EOL .   // The unique ID of the request.
    'cnames:' . var_export($result->cnames, true) . PHP_EOL // The list of custom domain names that are attached to the bucket.
);

Delete a CNAME record

The following code provides an example of how to delete a CNAME record.

<?php

// Import the autoload file to load dependency libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define the descriptions for command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region is required. It specifies the region where the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint is optional. It specifies the domain name that other services can use to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name is required.
];

// Generate a list of long options to parse command-line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // A colon (:) is added after each parameter to indicate that a value is required.
}, array_keys($optsdesc));

// Parse the command-line arguments.
$options = getopt("", $longopts);

// Check whether required parameters are missing.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Prompt the user that a required parameter is missing.
        exit(1);
    }
}

// Obtain the values of the command-line arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.

// Load credentials, including the AccessKey ID and AccessKey secret, from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();

// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Set the region.
$cfg->setRegion($region);

// If an endpoint is provided, set the endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Create a request object to delete a custom domain name that is attached to the bucket.
$request = new Oss\Models\DeleteCnameRequest(
    bucket: $bucket, // The bucket name.
    bucketCnameConfiguration: new Oss\Models\BucketCnameConfiguration(
        cname: new Oss\Models\Cname(
            domain: 'example.com' // The custom domain name to delete.
        )
    )
);

// Call the deleteCname method to delete the custom domain name that is attached to the bucket.
$result = $client->deleteCname($request);

// Print the result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code of the response.
    'request id:' . $result->requestId               // The unique ID of the request.
);

References

  • For more information about the API operation to create a CnameToken for domain name ownership verification, see CreateCnameToken.

  • For more information about the API operation to obtain a CnameToken, see GetCnameToken.

  • For more information about the API operation to add a CNAME record, see PutCname.

  • For more information about the API operation to query CNAME records, see ListCname.

  • For more information about the API operation to delete a CNAME record, see DeleteCname.