Todos os produtos
Search
Central de documentação

Object Storage Service:Static website hosting (C++ SDK)

Última atualização: Jul 03, 2026

Configure um bucket para hospedar um site estático. Após a configuração, as requisições ao endpoint do site servem o conteúdo diretamente do bucket. O sistema redireciona automaticamente para a página inicial padrão e para a página 404 padrão especificadas.

Observações

  • Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, utilize um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

  • Este tópico demonstra a criação de uma instância OssClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Criar uma instância OssClient.

  • Para definir a hospedagem de site estático, você precisa da permissão oss:PutBucketWebsite. Para obter a configuração de hospedagem de site estático, é necessária a permissão oss:GetBucketWebsite. Já para excluir essa configuração, utilize a permissão oss:DeleteBucketWebsite. Para mais informações, consulte Conceder políticas de acesso personalizadas a um usuário RAM.

Defina a hospedagem de site estático

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

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize OSS account information. */
    
    /* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the bucket name, for example, examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* Set static website hosting. */
    SetBucketWebsiteRequest request(BucketName);
    /* Set the default homepage for static website hosting to index.html. */
    request.setIndexDocument("index.html");
    /* Set the default 404 page for static website hosting to error.html. */
    request.setErrorDocument("error.html");

    auto outcome = client.SetBucketWebsite(request);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "SetBucketWebsite fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

Visualize a configuração de hospedagem de site estático

O código a seguir mostra como visualizar a configuração de hospedagem de site estático:

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize OSS account information. */
            
    /* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the bucket name, for example, examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* View the static website hosting configuration. */
    GetBucketWebsiteRequest request(BucketName);
    auto outcome = client.GetBucketWebsite(request);

    if (outcome.isSuccess()) {
        std::cout << "GetBucketWebsite success,IndexDocument: " << outcome.result().IndexDocument() <<
        " ,ErrorDocument: " << outcome.result().ErrorDocument() << std::endl;
    }
    else { 
        /* Handle exceptions. */
        std::cout << "GetBucketWebsite fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

Exclua a configuração de hospedagem de site estático

O código a seguir mostra como excluir a configuração de hospedagem de site estático:

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize OSS account information. */
    
    /* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the bucket name, for example, examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* Delete the static website hosting configuration. */
    DeleteBucketWebsiteRequest request(BucketName);

    auto outcome = client.DeleteBucketWebsite(request);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "DeleteBucketWebsite fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

Referências

  • Para acessar o código de exemplo completo sobre hospedagem de site estático, consulte o exemplo no GitHub.

  • Para mais detalhes sobre a operação de API destinada a configurar a hospedagem de site estático, consulte PutBucketWebsite.

  • Para obter informações sobre a operação de API usada para visualizar a configuração de hospedagem de site estático, consulte GetBucketWebsite.

  • Caso precise de dados sobre a operação de API para excluir a configuração de hospedagem de site estático, consulte DeleteBucketWebsite.