Todos los productos
Search
Centro de documentos

Object Storage Service:Asignación de nombres de dominio personalizados con OSS SDK for PHP 2.0

Última actualización: Sep 22, 2026

Cuando se cargan objetos en un bucket de Object Storage Service (OSS), se generan automáticamente direcciones URL que incluyen el endpoint público del bucket. Para acceder a estos objetos mediante un nombre de dominio personalizado, debe agregar un registro CNAME que asigne dicho dominio al bucket donde se almacenan los objetos.

Nota

  • Para acceder a los recursos de un bucket desde otros servicios de Alibaba Cloud dentro de la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints compatibles, consulte Regions and endpoints.

Código de ejemplo

Generar un token de CNAME

A continuación se muestra el código de ejemplo para generar un token de CNAME:

<?php

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

use AlibabaCloud\Oss\V2 as Oss;

// Define command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Define the endpoint for accessing OSS from other services.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Identify the target bucket by its name.
];

// Generate a list of long options for parsing command-line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // The colon (:) following each parameter indicates that the parameter is required. 
}, array_keys($optsdesc));

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

// Validate the required parameters.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Specifies that the required parameters are not configured.
        exit(1);
    }
}

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

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

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

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

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

// Specify the endpoint if one is provided.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

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

// Create a request object with necessary parameters for generating a CNAME token.
$request = new Oss\Models\CreateCnameTokenRequest(
    bucket: $bucket, // The name of the bucket.
    bucketCnameConfiguration: new Oss\Models\BucketCnameConfiguration(
        cname: new Oss\Models\Cname(
            domain: 'example.com' // The custom domain name.
        )
    )
);

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

// Output the result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code.
    '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.
);

Consultar un token de CNAME

A continuación se muestra el código de ejemplo para consultar un token de CNAME:

<?php

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

use AlibabaCloud\Oss\V2 as Oss;

// Define command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Define the endpoint for accessing OSS from other services.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Identify the target bucket by its name.
];

// Generate a list of long options for parsing command-line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // The colon (:) following each parameter indicates that the parameter is required.
}, array_keys($optsdesc));

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

// Validate the required parameters.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Specifies that the required parameters are not configured.
        exit(1);
    }
}

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

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

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

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

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

// Specify the endpoint if one is provided.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

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

// Create a request object with necessary parameters for querying a CNAME token.
$request = new Oss\Models\GetCnameTokenRequest(
    bucket: $bucket, // The name of the bucket.
    cname: 'example.com' // The custom domain name.
);

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

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

Configurar un registro CNAME

Asignar un nombre de dominio personalizado

<?php

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

use AlibabaCloud\Oss\V2 as Oss;

// Define command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Define the endpoint for accessing OSS from other services.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Identify the target bucket by its name.
];

// Generate a list of long options for parsing command-line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // The colon (:) following each parameter indicates that the parameter is required.
}, array_keys($optsdesc));

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

// Validate the required parameters.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Specifies that the required parameters are not configured.
        exit(1);
    }
}

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

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

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

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

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

// Specify the endpoint if one is provided.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

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

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

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

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

Asignar un nombre de dominio personalizado y asociar un certificado

<?php

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

use AlibabaCloud\Oss\V2 as Oss;

// Define command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Define the endpoint for accessing OSS from other services.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Identify the target bucket by its name.
];

// Generate a list of long options for parsing command-line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // The colon (:) following each parameter indicates that the parameter is required.
}, array_keys($optsdesc));

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

// Validate the required parameters.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Specifies that the required parameters are not configured.
        exit(1);
    }
}

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

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

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

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

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

// Specify the endpoint if one is provided.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

$request = new Oss\Models\PutCnameRequest(
    bucket: $bucketName, // The name of the bucket.
    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, // Specify 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 map the custom domain name to the bucket.
$result = $client->putCname($request);

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

Desasociar un certificado

Si el certificado ya no es necesario, puede desasociarlo del nombre de dominio.

<?php

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

use AlibabaCloud\Oss\V2 as Oss;

// Define command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Define the endpoint for accessing OSS from other services.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Identify the target bucket by its name.
];

// Generate a list of long options for parsing command-line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // The colon (:) following each parameter indicates that the parameter is required.
}, array_keys($optsdesc));

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

// Validate the required parameters.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Specifies that the required parameters are not configured.
        exit(1);
    }
}

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

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

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

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

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

// Specify the endpoint if one is provided.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create a request object with necessary parameters for disassociating a certificate.
$request = new Oss\Models\PutCnameRequest(
    bucket: $bucketName, // The name of the bucket.
    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 // Disassociate the certificate.
            )
        )
    )
);

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

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

Listar registros CNAME

A continuación se muestra el código de ejemplo para listar los registros CNAME asociados a un bucket:

<?php

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

use AlibabaCloud\Oss\V2 as Oss;

// Define command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Define the endpoint for accessing OSS from other services.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Identify the target bucket by its name.
];

// Generate a list of long options for parsing command-line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // The colon (:) following each parameter indicates that the parameter is required.
}, array_keys($optsdesc));

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

// Validate the required parameters.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Specifies that the required parameters are not configured.
        exit(1);
    }
}

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

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

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

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

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

// Specify the endpoint if one is provided.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

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

// Create a request object with necessary parameters for listing the custom domain names mapped to the bucket.
$request = new Oss\Models\ListCnameRequest(
    bucket: $bucket // The name of the bucket.
);

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

// Output the result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code.
    '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 mapped to the bucket.
);

Eliminar un registro CNAME

A continuación se muestra el código de ejemplo para eliminar un registro CNAME:

<?php

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

use AlibabaCloud\Oss\V2 as Oss;

// Define command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Define the endpoint for accessing OSS from other services.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Identify the target bucket by its name.
];

// Generate a list of long options for parsing command-line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // The colon (:) following each parameter indicates that the parameter is required.
}, array_keys($optsdesc));

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

// Validate the required parameters.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Specifies that the required parameters are not configured.
        exit(1);
    }
}

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

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

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

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

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

// Specify the endpoint if one is provided.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

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

// Create a request object with necessary parameters for deleting the CNAME record.
$request = new Oss\Models\DeleteCnameRequest(
    bucket: $bucket, // The name of the bucket.
    bucketCnameConfiguration: new Oss\Models\BucketCnameConfiguration(
        cname: new Oss\Models\Cname(
            domain: 'example.com' // The CNAME record to delete.
        )
    )
);

// Call the deleteCname method to delete the CNAME record.
$result = $client->deleteCname($request);

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

Referencias

Para obtener más información sobre las API relacionadas, consulte los siguientes temas: