Todos os produtos
Search
Central de documentação

Object Storage Service:Mapear nomes de domínio personalizados com o OSS SDK for PHP 2.0

Última atualização: Jul 03, 2026

Ao fazer upload de objetos para um bucket do Object Storage Service (OSS), o sistema gera automaticamente URLs que incorporam o endpoint público do bucket. Para acessar esses objetos por meio de um nome de domínio personalizado, adicione um registro CNAME para mapear o domínio personalizado ao bucket onde os objetos estão armazenados.

Nota

  • Para acessar recursos em um bucket a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter detalhes sobre as regiões e endpoints compatíveis, consulte Regiões e endpoints.

Código de exemplo

Gerar um token CNAME

O código abaixo gera um token 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 um token CNAME

O código abaixo consulta um token 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 um registro CNAME

Mapear um nome de domínio 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.
);

Mapear um nome de domínio personalizado e associar um 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.
);

Desassociar um certificado

Se o certificado não for mais necessário, desassocie-o do nome de domínio.

<?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

O código abaixo lista os registros CNAME associados a um 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.
);

Excluir um registro CNAME

O código abaixo exclui um 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.
);

Referências

Para mais informações sobre as APIs relacionadas, consulte os tópicos a seguir: