Vous pouvez configurer un bucket pour l'hébergement de site web statique et définir des règles de redirection (RoutingRule) pour le rétrolien par miroir. Une fois l'hébergement de site web statique activé, les requêtes adressées au site web équivalent à des requêtes vers le bucket. Vous pouvez également configurer des redirections automatiques vers une page d'index et une page d'erreur spécifiques. Les règles de redirection pour le rétrolien par miroir facilitent la migration transparente des données vers Object Storage Service (OSS).
Notes
Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Si vous souhaitez accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région qu'OSS, 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.
Dans cette rubrique, les identifiants d'accès sont obtenus à partir des variables d'environnement. Pour plus d'informations sur la configuration des identifiants d'accès, consultez Configurer les identifiants d'accès.
Cette rubrique illustre la création d'une instance OSSClient avec un endpoint OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Configurer un client (Go SDK V1).
Pour configurer l'hébergement de site web statique ou le rétrolien par miroir, vous devez disposer de l'autorisation
oss:PutBucketWebsite. Pour récupérer la configuration de l'hébergement de site web statique ou du rétrolien par miroir, vous devez disposer de l'autorisationoss:GetBucketWebsite. Pour supprimer la configuration de l'hébergement de site web statique ou du rétrolien par miroir, vous devez disposer de l'autorisationoss:DeleteBucketWebsite. Pour plus d'informations, consultez Accorder des stratégies d'accès personnalisées aux utilisateurs RAM.
Hébergement de site web statique
Les sites web statiques sont des sites dont toutes les pages ne contiennent que du contenu statique, y compris des scripts tels que le code JavaScript pouvant être exécuté côté client. Vous pouvez utiliser la fonctionnalité d'hébergement de site web statique pour héberger votre site web statique dans un bucket OSS et accéder au site 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 :
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) } } -
Interroger les configurations d'hébergement de site web statique
L'exemple de code suivant montre comment interroger les configurations d'hébergement de site web statique :
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) } -
Supprimer les configurations d'hébergement de site web statique
L'exemple de code suivant montre comment supprimer les configurations d'hébergement de site web statique :
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) } }
Rétrolien par miroir
Le rétrolien par miroir est principalement utilisé pour la migration transparente des données vers OSS. Par exemple, votre service peut s'exécuter sur votre propre serveur d'origine ou sur un autre produit cloud. Si vous souhaitez migrer le service vers OSS pour le développement de votre activité, vous devez garantir la continuité du service pendant la migration. Durant celle-ci, vous pouvez utiliser des règles de rétrolien par miroir pour récupérer les données qui n'ont pas encore été migrées vers OSS. Cela garantit le bon fonctionnement de votre service.
-
Configurer les règles de rétrolien par miroir
Si un demandeur tente d'accéder à un objet dans le bucket spécifié et que cet objet n'existe pas, vous pouvez spécifier l'URL de l'objet sur le serveur d'origine ainsi que les conditions de rétrolien pour permettre au demandeur d'obtenir l'objet depuis l'origine. Par exemple, un bucket nommé examplebucket se trouve dans la région Chine (Hangzhou). Lorsqu'un demandeur tente d'accéder à un objet dans le répertoire examplefolder du répertoire racine du bucket et que l'objet n'existe pas, le demandeur est redirigé vers www.example.com pour accéder à l'objet stocké dans le répertoire examplefolder du serveur d'origine.
L'exemple de code suivant montre comment configurer les règles de rétrolien par miroir pour le scénario précédent :
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) } } -
Interroger les configurations de rétrolien par miroir
L'exemple de code suivant montre comment interroger les configurations de rétrolien par miroir :
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) } -
Supprimer les configurations de rétrolien par miroir
L'exemple de code suivant montre comment supprimer les configurations de rétrolien par miroir :
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) } }
Références
Pour obtenir l'exemple de code complet utilisé pour gérer l'hébergement de site web statique et le rétrolien par miroir, visitez GitHub.
Pour plus d'informations sur l'opération API utilisée pour configurer l'hébergement de site web statique ou le rétrolien par miroir, consultez PutBucketWebsite.
Pour plus d'informations sur l'opération API utilisée pour récupérer la configuration de l'hébergement de site web statique ou du rétrolien par miroir, consultez GetBucketWebsite.
Pour plus d'informations sur l'opération API utilisée pour supprimer la configuration de l'hébergement de site web statique ou du rétrolien par miroir, consultez DeleteBucketWebsite.