Configure um bucket para hospedagem de site estático e defina regras de redirecionamento (RoutingRule) para back-to-origin baseado em espelhamento. Após ativar a hospedagem de site estático, as solicitações ao site equivalem às solicitações ao bucket. Também é possível configurar redirecionamentos automáticos para uma página de índice e uma página de erro específicas. As regras de redirecionamento para back-to-origin baseado em espelhamento facilitam a migração contínua de dados para o Object Storage Service (OSS).
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, use um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Neste exemplo, as credenciais de acesso são obtidas de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso.
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 Configurar um cliente (Go SDK V1).
Para configurar a hospedagem de site estático ou o back-to-origin baseado em espelhamento, você precisa da permissão
oss:PutBucketWebsite. Para consultar a configuração de hospedagem de site estático ou back-to-origin baseado em espelhamento, você precisa da permissãooss:GetBucketWebsite. Para excluir essa configuração, você precisa da permissãooss:DeleteBucketWebsite. Para obter mais informações, consulte Conceder políticas de acesso personalizadas a usuários RAM.
Hospedagem de site estático
Sites estáticos são compostos exclusivamente por conteúdo estático, incluindo scripts como código JavaScript executado no cliente. Com o recurso de hospedagem de site estático, você hospeda seu site em um bucket do OSS e o acessa pelo nome de domínio do bucket.
-
Configure a hospedagem de site estático
O código de exemplo abaixo mostra como configurar a hospedagem de site estático:
package main import ( "fmt" "os" "github.com/aliyun/aliyun-oss-go-sdk/oss" ) func main() { // 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. provider, err := oss.NewEnvironmentVariableCredentialsProvider() if err != nil { fmt.Println("Error:", err) os.Exit(-1) } // Create an OSSClient instance. // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region. clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)} clientOptions = append(clientOptions, oss.Region("yourRegion")) // Specify the version of the signature algorithm. clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4)) client, err := oss.New("yourEndpoint", "", "", clientOptions...) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } // Specify the name of the bucket. Example: examplebucket. bucketName := "examplebucket" // Set the default homepage to index.html and the default 404 page to error.html for the static website. err = client.SetBucketWebsite(bucketName, "index.html", "error.html") if err != nil { fmt.Println("Error:", err) os.Exit(-1) } } -
Consultar configurações de hospedagem de site estático
O exemplo a seguir ilustra como consultar as configurações de hospedagem de site estático:
package main import ( "fmt" "os" "github.com/aliyun/aliyun-oss-go-sdk/oss" ) func main() { // 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. provider, err := oss.NewEnvironmentVariableCredentialsProvider() if err != nil { fmt.Println("Error:", err) os.Exit(-1) } // Create an OSSClient instance. // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region. clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)} clientOptions = append(clientOptions, oss.Region("yourRegion")) // Specify the version of the signature algorithm. clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4)) client, err := oss.New("yourEndpoint", "", "", clientOptions...) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } // Specify the name of the bucket. Example: examplebucket. bucketName := "examplebucket" // Query static website hosting configurations. wsRes, err := client.GetBucketWebsite(bucketName) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } fmt.Println("indexWebsite: ", wsRes.IndexDocument.Suffix) fmt.Println("errorWebsite: ", wsRes.ErrorDocument.Key) } -
Exclua as configurações de hospedagem de site estático
Use o código abaixo como referência para excluir as configurações de hospedagem de site estático:
package main import ( "fmt" "os" "github.com/aliyun/aliyun-oss-go-sdk/oss" ) func main() { // 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. provider, err := oss.NewEnvironmentVariableCredentialsProvider() if err != nil { fmt.Println("Error:", err) os.Exit(-1) } // Create an OSSClient instance. // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region. clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)} clientOptions = append(clientOptions, oss.Region("yourRegion")) // Specify the version of the signature algorithm. clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4)) client, err := oss.New("yourEndpoint", "", "", clientOptions...) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } // Specify the name of the bucket. Example: examplebucket. bucketName := "examplebucket" // Delete static website hosting configurations. err = client.DeleteBucketWebsite(bucketName) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } }
Back-to-origin baseado em espelhamento
O back-to-origin baseado em espelhamento é usado principalmente para migrar dados para o OSS sem interrupções. Suponha que seu serviço esteja em execução em um servidor de origem próprio ou em outro produto de nuvem. Ao migrar esse serviço para o OSS visando o desenvolvimento de negócios, garanta que ele continue funcionando durante a transição. Nesse período, utilize regras de back-to-origin baseado em espelhamento para recuperar dados ainda não migrados e assegurar o funcionamento correto do serviço.
-
Configure as regras de back-to-origin baseado em espelhamento
Quando um solicitante tenta acessar um objeto no bucket especificado e esse objeto não existe, especifique a URL do objeto na origem e as condições de back-to-origin para permitir que o solicitante obtenha o objeto diretamente da origem. Por exemplo, considere um bucket chamado examplebucket na região China (Hangzhou). Se um solicitante tentar acessar um objeto no diretório examplefolder, na raiz do bucket, e o objeto não existir, o solicitante será redirecionado para www.example.com para acessar o objeto armazenado no diretório examplefolder da origem.
O código a seguir exemplifica como configurar regras de back-to-origin baseado em espelhamento para o cenário descrito acima:
package main import ( "fmt" "os" "github.com/aliyun/aliyun-oss-go-sdk/oss" ) func main() { // 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. provider, err := oss.NewEnvironmentVariableCredentialsProvider() if err != nil { fmt.Println("Error:", err) os.Exit(-1) } // Create an OSSClient instance. // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region. clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)} clientOptions = append(clientOptions, oss.Region("yourRegion")) // Specify the version of the signature algorithm. clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4)) client, err := oss.New("yourEndpoint", "", "", clientOptions...) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } // Specify the name of the bucket. Example: examplebucket. bucketName := "examplebucket" var indexWebsite = "myindex.html" var errorWebsite = "myerror.html" btrue := true bfalse := false // Set the back-to-origin type to mirroring-based back-to-origin. ruleOk := oss.RoutingRule{ RuleNumber: 1, Condition: oss.Condition{ KeyPrefixEquals: "", // Set the back-to-origin condition to HTTP status code 404. HTTPErrorCodeReturnedEquals: 404, }, Redirect: oss.Redirect{ RedirectType: "Mirror", // PassQueryString: &btrue, // Specify the back-to-origin URL for a mirroring-based back-to-origin rule. MirrorURL: "http://www.test.com/", // MirrorPassQueryString:&btrue, // MirrorFollowRedirect:&bfalse, // MirrorCheckMd5:&bfalse, MirrorHeaders: oss.MirrorHeaders{ // PassAll:&bfalse, // Transmit specific HTTP headers. Pass: []string{"myheader-key1", "myheader-key2"}, // Prohibit the transmission of specific HTTP headers. Remove: []string{"myheader-key3", "myheader-key4"}, Set: []oss.MirrorHeaderSet{ { Key: "myheader-key5", Value: "myheader-value5", }, }, }, }, } // Set the back-to-origin type to redirection-based back-to-origin. ruleArrOk := []oss.RoutingRule{ { RuleNumber: 2, Condition: oss.Condition{ // Set the back-to-origin condition to HTTP status code 404 and the prefix in object names to abc/. KeyPrefixEquals: "abc/", HTTPErrorCodeReturnedEquals: 404, IncludeHeader: []oss.IncludeHeader{ { Key: "host", Equals: "test.oss-cn-beijing-internal.aliyuncs.com", }, }, }, Redirect: oss.Redirect{ RedirectType: "AliCDN", Protocol: "http", HostName: "www.test.com", PassQueryString: &bfalse, ReplaceKeyWith: "prefix/${key}.suffix", HttpRedirectCode: 301, }, }, // Set the back-to-origin type to mirroring-based back-to-origin. { RuleNumber: 3, Condition: oss.Condition{ KeyPrefixEquals: "", HTTPErrorCodeReturnedEquals: 404, }, Redirect: oss.Redirect{ RedirectType: "Mirror", PassQueryString: &btrue, MirrorURL: "http://www.test.com/", MirrorPassQueryString: &btrue, MirrorFollowRedirect: &bfalse, MirrorCheckMd5: &bfalse, MirrorHeaders: oss.MirrorHeaders{ PassAll: &btrue, Pass: []string{"myheader-key1", "myheader-key2"}, Remove: []string{"myheader-key3", "myheader-key4"}, Set: []oss.MirrorHeaderSet{ { Key: "myheader-key5", Value: "myheader-value5", }, }, }, }, }, } wxmlOne := oss.WebsiteXML{ IndexDocument: oss.IndexDocument{ Suffix: indexWebsite, }, ErrorDocument: oss.ErrorDocument{ Key: errorWebsite, }, } wxmlOne.RoutingRules = append(wxmlOne.RoutingRules, ruleOk) wxmlOne.RoutingRules = append(wxmlOne.RoutingRules, ruleArrOk...) err = client.SetBucketWebsiteDetail(bucketName, wxmlOne) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } } -
Consultar configurações de back-to-origin baseado em espelhamento
Veja no exemplo abaixo como consultar as configurações de back-to-origin baseado em espelhamento:
package main import ( "fmt" "os" "github.com/aliyun/aliyun-oss-go-sdk/oss" ) func main() { // 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. provider, err := oss.NewEnvironmentVariableCredentialsProvider() if err != nil { fmt.Println("Error:", err) os.Exit(-1) } // Create an OSSClient instance. // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region. clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)} clientOptions = append(clientOptions, oss.Region("yourRegion")) // Specify the version of the signature algorithm. clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4)) client, err := oss.New("yourEndpoint", "", "", clientOptions...) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } // Specify the name of the bucket. Example: examplebucket. bucketName := "examplebucket" // Query mirroring-based back-to-origin configurations. data,err := client.GetBucketWebsiteXml(bucketName) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } fmt.Println(data) } -
Exclua as configurações de back-to-origin baseado em espelhamento
Siga o modelo de código a seguir para excluir as configurações de back-to-origin baseado em espelhamento:
package main import ( "fmt" "os" "github.com/aliyun/aliyun-oss-go-sdk/oss" ) func main() { // 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. provider, err := oss.NewEnvironmentVariableCredentialsProvider() if err != nil { fmt.Println("Error:", err) os.Exit(-1) } // Create an OSSClient instance. // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region. clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)} clientOptions = append(clientOptions, oss.Region("yourRegion")) // Specify the version of the signature algorithm. clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4)) client, err := oss.New("yourEndpoint", "", "", clientOptions...) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } // Specify the name of the bucket. Example: examplebucket. bucketName := "examplebucket" // Delete mirroring-based back-to-origin configurations. err = client.DeleteBucketWebsite(bucketName) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } }
Referências
Acesse o GitHub para visualizar o código de exemplo completo sobre gerenciamento de hospedagem de site estático e back-to-origin baseado em espelhamento.
Para detalhes sobre a operação de API usada para configurar hospedagem de site estático ou back-to-origin baseado em espelhamento, consulte PutBucketWebsite.
Saiba mais sobre a operação de API para recuperar configurações de hospedagem de site estático ou back-to-origin baseado em espelhamento em GetBucketWebsite.
Informações adicionais sobre a operação de API para excluir configurações de hospedagem de site estático ou back-to-origin baseado em espelhamento estão disponíveis em DeleteBucketWebsite.