Tous les produits
Search
Centre de documentation

Object Storage Service:Hébergement de site web statique avec le SDK OSS pour PHP 2.0

Dernière mise à jour :Aug 18, 2026

Object Storage Service (OSS) vous permet d'héberger des sites web statiques sur des buckets et de configurer des règles de retour à la source par mise en miroir. Lorsque l'hébergement de site web statique est activé, les visiteurs du bucket sont automatiquement redirigés vers la page d'accueil par défaut ou la page d'erreur 404 par défaut spécifiée. Les règles de retour à la source par mise en miroir permettent une migration transparente des données vers OSS.

Notes d'utilisation

  • L'exemple de code de cette rubrique utilise l'ID de région cn-hangzhou de la région Chine (Hangzhou). Par défaut, le point de terminaison public sert à accéder aux ressources d'un bucket. Pour accéder aux ressources du bucket depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un point de terminaison interne. Pour plus d'informations sur les régions et les points de terminaison OSS, consultez Régions et points de terminaison.

  • Pour configurer l'hébergement de site web statique ou le retour à la source par mise en miroir, vous devez disposer de l'autorisation oss:PutBucketWebsite. Pour consulter les configurations d'hébergement de site web statique ou les règles de retour à la source par mise en miroir, vous devez disposer de l'autorisation oss:GetBucketWebsite. Pour supprimer les configurations d'hébergement de site web statique ou les règles de retour à la source par mise en miroir, vous devez disposer de l'autorisation oss:DeleteBucketWebsite. Pour plus d'informations, consultez Accorder une politique personnalisée.

Gérer l'hébergement de site web statique

Les sites web statiques sont constitués exclusivement de contenu statique, y compris des scripts côté client tels que JavaScript. Vous pouvez héberger un site web statique dans un bucket OSS et y accéder via le nom de domaine du bucket.

Configurer l'hébergement de site web statique

L'exemple de code suivant montre comment configurer l'hébergement de site web statique :

<?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.
);

Consulter les configurations d'hébergement de site web statique d'un bucket

L'exemple de code suivant montre comment consulter les configurations d'hébergement de site web statique d'un 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.
);

Supprimer les configurations d'hébergement de site web statique d'un bucket

L'exemple de code suivant montre comment supprimer les configurations d'hébergement de site web statique d'un 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.
);

Gérer le retour à la source par mise en miroir

Le retour à la source par mise en miroir permet une migration transparente des données vers OSS depuis une source d'origine gérée par vos soins ou un autre service cloud, sans interruption de service. Pendant la migration, toutes les données non encore migrées vers OSS sont récupérées de manière transparente depuis la source d'origine, garantissant ainsi la continuité des activités.

Configurer les règles de retour à la source par mise en miroir pour un bucket

Si un demandeur accède à un objet qui n'existe pas dans le bucket spécifié, vous pouvez spécifier l'URL de l'objet dans la source d'origine et les conditions de retour à la source pour récupérer l'objet depuis cette source. Par exemple, si un bucket nommé examplebucket se trouve dans la région Chine (Hangzhou) et qu'un demandeur accède à un objet inexistant dans le répertoire examplefolder du répertoire racine du bucket, le demandeur est redirigé vers www.example.com pour accéder à l'objet stocké dans le répertoire examplefolder de la source d'origine.

L'exemple de code suivant montre comment configurer les règles de retour à la source par mise en miroir dans ce scénario :

<?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.
);

Consulter les règles de retour à la source par mise en miroir d'un bucket

L'exemple de code suivant montre comment consulter les règles de retour à la source par mise en miroir d'un 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.
);

Supprimer les règles de retour à la source par mise en miroir d'un bucket

L'exemple de code suivant montre comment supprimer les règles de retour à la source par mise en miroir d'un 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.
);

Références

  • Pour obtenir le code complet d'exemple de gestion de l'hébergement de site web statique et du retour à la source par mise en miroir, visitez put_bucket_website, get_bucket_website et delete_bucket_website.

  • Pour plus d'informations sur l'opération API permettant de configurer l'hébergement de site web statique ou le retour à la source par mise en miroir, consultez PutBucketWebsite.

  • Pour plus d'informations sur l'opération API permettant de consulter les configurations d'hébergement de site web statique ou les règles de retour à la source par mise en miroir, consultez GetBucketWebsite.

  • Pour plus d'informations sur l'opération API permettant de supprimer les configurations d'hébergement de site web statique ou les règles de retour à la source par mise en miroir, consultez DeleteBucketWebsite.