Todos os produtos
Search
Central de documentação

Object Storage Service:Hospedagem de site estático usando o OSS SDK for PHP 2.0

Última atualização: Sep 22, 2026

O Object Storage service (OSS) permite crie sites estáticos em buckets e defina regras de back-to-origin baseadas em espelhamento. Quando a hospedagem de site estático está ative, os visitantes do bucket são redirecionados automaticamente para a página inicial padrão ou a página 404 padrão especificada. As regras de back-to-origin baseadas em espelhamento permitem a migração contínua de dados para o OSS.

Notas de uso

  • O código de exemplo neste tópico usa o ID da região cn-hangzhou da região china (Hangzhou). Por padrão, o endpoint público é utilizado para acessar os recursos de um bucket. Para acessar recursos no bucket por meio de outros serviços da alibaba cloud na mesma região do bucket, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.

  • Para defina a hospedagem de site estático ou o back-to-origin baseado em espelhamento, é necessário ter a permissão oss:PutBucketWebsite. Para consultar as configurações de hospedagem de site estático ou as regras de back-to-origin baseadas em espelhamento, é necessário ter a permissão oss:GetBucketWebsite. Para exclua as configurações de hospedagem de site estático ou as regras de back-to-origin baseadas em espelhamento, é necessário ter a permissão oss:DeleteBucketWebsite. Para mais informações, consulte Grant a custom policy.

Gerencie a hospedagem de site estático

Sites estáticos consistem inteiramente de conteúdo estático, incluindo scripts do lado do cliente, como JavaScript. Você pode hospedar um site estático em um bucket do OSS e acessá-lo por meio do nome de domínio do bucket.

configure a hospedagem de site estático

O código de exemplo a seguir mostra como defina a hospedagem de site estático:

<?php

// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line parameters.
$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) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
];

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

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

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

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

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

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

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

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

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

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

// Create a PutBucketWebsiteRequest object to configure static website hosting for the bucket.
$request = new Oss\Models\PutBucketWebsiteRequest(bucket: $bucket,
    websiteConfiguration: new Oss\Models\WebsiteConfiguration(
        indexDocument: new Oss\Models\IndexDocument(
            suffix: 'index.html', // Specify the name of the file that is used as the default homepage.
            supportSubDir: true, // Enable the subdirectory homepage feature for the bucket.
            type: 0 // The type of the index page.
        ),
        errorDocument: new Oss\Models\ErrorDocument(
            key: 'error.html', // The name of the file that is used as the default 404 page.
            httpStatus: 404 // The HTTP status code returned on the default 404 page.
        )
    )
);

// Use the putBucketWebsite method to configure static website hosting for the bucket.
$result = $client->putBucketWebsite($request);

// Display the returned result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The returned HTTP status code.
    'request id:' . $result->requestId // The request ID of the request, which is the unique identifier of the request.
);

Consulte as configurações de hospedagem de site estático de um bucket

O código de exemplo a seguir mostra como consultar as configurações de hospedagem de site estático de um bucket:

<?php

// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line parameters.
$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) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
];

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

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

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

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

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

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

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

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

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

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

// Create a GetBucketWebsiteRequest object to query the static website hosting configurations of the bucket.
$request = new Oss\Models\GetBucketWebsiteRequest(bucket: $bucket);

// Use the getBucketWebsite method to query the static website hosting configurations of the bucket.
$result = $client->getBucketWebsite($request);

// Display the returned result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The returned HTTP status code.
    'request id:' . $result->requestId . PHP_EOL . // The request ID of the request, which is the unique identifier of the request.
    'website config:' . var_export($result->websiteConfiguration, true) . PHP_EOL // The static website hosting configurations.
);

exclua as configurações de hospedagem de site estático de um bucket

O código de exemplo a seguir mostra como exclua as configurações de hospedagem de site estático de um bucket:

<?php

// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line parameters.
$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) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
];

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

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

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

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

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

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

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

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

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

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

// Create a DeleteBucketWebsiteRequest object to delete the static website hosting configurations of the bucket.
$request = new Oss\Models\DeleteBucketWebsiteRequest(bucket: $bucket);

// Use the deleteBucketWebsite method to delete the static website hosting configurations of the bucket.
$result = $client->deleteBucketWebsite($request);

// Display the returned result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The returned HTTP status code.
    'request id:' . $result->requestId // The request ID of the request, which is the unique identifier of the request.
);

Gerencie o back-to-origin baseado em espelhamento

O back-to-origin baseado em espelhamento permite a migração contínua de dados para o OSS a partir de uma origem autogerenciada ou de outro service de cloud sem interrupções. Durante a migração, quaisquer dados ainda não migrados para o OSS são recuperados de forma transparente da origem, garantindo a continuidade dos negócios.

configure regras de back-to-origin baseadas em espelhamento para um bucket

Se um solicitante acessar um objeto que não existe no bucket especificado, especifique a URL do objeto na origem e as condições de back-to-origin para recuperar o objeto da origem. Por exemplo, se um bucket chamado examplebucket estiver localizado na região china (Hangzhou) e um solicitante acessar um objeto inexistente no diretório examplefolder do diretório raiz do bucket, o solicitante será redirecionado para www.example.com para acessar o objeto armazenado no diretório examplefolder da origem.

O código de exemplo a seguir mostra como defina regras de back-to-origin baseadas em espelhamento neste cenário:

<?php

// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line parameters.
$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) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
];

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

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

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

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

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

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

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

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

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

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

// Specify mirroring-based back-to-origin rules.
$ruleOk = new Oss\Models\RoutingRule(
    ruleNumber: 1, // The rule number.
    condition: new Oss\Models\RoutingRuleCondition(
        keyPrefixEquals: 'myobject', // Specify the prefix contained in the names of the objects that you want to retrieve.
        httpErrorCodeReturnedEquals: 404 // Set the back-to-origin condition to HTTP status code 404.
    ),
    redirect: new Oss\Models\RoutingRuleRedirect(
        redirectType: 'Mirror', // Set the redirection type to Mirror.
        mirrorURL: 'http://www.test.com/', // Specify the origin URL.
        mirrorHeaders: new Oss\Models\MirrorHeaders(
            passAll: false, // Specify whether to transmit all HTTP headers.
            passs: ['myheader-key1', 'myheader-key2'], // Specify the HTTP headers that can be transmitted.
            removes: ['myheader-key3', 'myheader-key4'], // Specify the HTTP headers that cannot be transmitted.
            sets: [
                new Oss\Models\MirrorHeadersSet(
                    key: 'myheader-key5', // Specify the names of the specified HTTP headers.
                    value: 'myheader-value' // Specify the values of the specified HTTP headers.
                ),
            ]
        )
    )
);

// Create a PutBucketWebsite request.
$request = new Oss\Models\PutBucketWebsiteRequest(
    bucket: $bucketName, // The name of the bucket.
    websiteConfiguration: new Oss\Models\WebsiteConfiguration(
        indexDocument: new Oss\Models\IndexDocument(
            suffix: 'index.html', // The default homepage for the mirroring-based back-to-origin request.
            supportSubDir: true,
            type: 0
        ),
        errorDocument: new Oss\Models\ErrorDocument(
            key: 'error.html', // The default 404 page for the mirroring-based back-to-origin request.
            httpStatus: 404
        ),
        routingRules: new Oss\Models\RoutingRules(
            routingRules: [$ruleOk] // The mirroring-based back-to-origin rules.
        )
    )
);

// Execute the PutBucketWebsite request.
$result = $client->putBucketWebsite($request);

// Display the returned result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The returned HTTP status code.
    'request id:' . $result->requestId . PHP_EOL . // The request ID of the request, which is the unique identifier of the request.
    'website config:' . var_export($result->websiteConfiguration, true) . PHP_EOL // The static website hosting configurations.
);

Consulte as regras de back-to-origin baseadas em espelhamento de um bucket

O código de exemplo a seguir mostra como consultar as regras de back-to-origin baseadas em espelhamento de um bucket:

<?php

// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line parameters.
$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) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
];

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

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

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

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

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

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

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

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

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

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

// Create a GetBucketWebsite request.
$request = new Oss\Models\GetBucketWebsiteRequest(
    bucket: $bucketName, // The name of the bucket.
);

// Execute the GetBucketWebsite request.
$result = $client->getBucketWebsite($request);

// Display the returned result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The returned HTTP status code.
    'request id:' . $result->requestId . PHP_EOL . // The request ID of the request, which is the unique identifier of the request.
    'website config:' . var_export($result->websiteConfiguration, true) . PHP_EOL // The static website hosting configurations.
);

exclua as regras de back-to-origin baseadas em espelhamento de um bucket

O código de exemplo a seguir mostra como exclua as regras de back-to-origin baseadas em espelhamento de um bucket:

<?php

// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line parameters.
$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) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
];

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

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

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

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

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

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

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

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

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

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

// Create a DeleteBucketWebsite request.
$request = new Oss\Models\DeleteBucketWebsiteRequest(
    bucket: $bucketName, // The name of the bucket.
);

// Use the deleteBucketWebsite method to delete the static website hosting configurations of the bucket.
$result = $client->deleteBucketWebsite($request);

// Display the returned result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The returned HTTP status code.
    'request id:' . $result->requestId // The request ID of the request, which is the unique identifier of the request.
);

Referências

  • Para o código de exemplo completo sobre o gerenciamento de hospedagem de site estático e back-to-origin baseado em espelhamento, visite put_bucket_website, get_bucket_website e delete_bucket_website.

  • Para mais informações sobre a operação de API que você pode chamar para defina a hospedagem de site estático ou o back-to-origin baseado em espelhamento, consulte PutBucketWebsite.

  • Para mais informações sobre a operação de API que você pode chamar para consultar as configurações de hospedagem de site estático ou as regras de back-to-origin baseadas em espelhamento, consulte GetBucketWebsite.

  • Para mais informações sobre a operação de API que você pode chamar para exclua as configurações de hospedagem de site estático ou as regras de back-to-origin baseadas em espelhamento, consulte DeleteBucketWebsite.