Tous les produits
Search
Centre de documentation

Object Storage Service:Hébergement de site web statique (back-to-origin par miroir) (SDK Go V2)

Dernière mise à jour :Aug 18, 2026

Configurez un bucket pour l'hébergement de site web statique et définissez des règles de routage pour le back-to-origin par miroir. Une fois activé, OSS sert directement le contenu statique depuis le bucket et redirige les requêtes vers les pages d'index et d'erreur configurées.

Notes d'utilisation

  • Les exemples de code de cette rubrique utilisent l'ID de région cn-hangzhou, qui correspond à la région Chine (Hangzhou). Par défaut, un endpoint public est utilisé. Pour accéder à OSS depuis d'autres services Alibaba Cloud au sein de la même région, utilisez plutôt un endpoint interne. Pour obtenir la liste complète des régions et endpoints pris en charge, consultez Régions et endpoints.

  • Les exemples lisent les identifiants d'accès à partir des variables d'environnement. Pour les instructions de configuration, consultez Configurer les identifiants d'accès.

  • Les permissions Resource Access Management (RAM) suivantes sont requises :

    • oss:PutBucketWebsite : nécessaire pour configurer l'hébergement de site web statique ou le back-to-origin par miroir.

    • oss:GetBucketWebsite : nécessaire pour interroger les configurations d'hébergement de site web statique ou de back-to-origin par miroir.

    • oss:DeleteBucketWebsite : nécessaire pour supprimer les configurations d'hébergement de site web statique ou de back-to-origin par miroir.

    Pour obtenir des instructions sur l'attribution de ces permissions, consultez Attacher une politique à un utilisateur RAM.

Hébergement de site web statique

Un site web statique diffuse du contenu fixe (pages HTML, images, CSS et scripts côté client) sans traitement côté serveur. Cette section couvre les trois opérations suivantes : PutBucketWebsite, GetBucketWebsite et DeleteBucketWebsite.

Configurer

L'exemple ci-dessous configure un bucket pour l'hébergement de site web statique. Il définit index.html comme page d'index et error.html comme page d'erreur 404. Enregistrez ce fichier sous le nom put_bucket_website.go.

Pour l'exemple exécutable complet, consultez put_bucket_website.go sur GitHub.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // The region where the bucket is located.
	bucketName string // The name of the bucket.
)

// The init function initializes command-line flags.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse the command-line flags.
	flag.Parse()

	// Check if the bucket name is provided.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check if the region is provided.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load default configurations and set the credentials provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to configure static website hosting for the bucket.
	request := &oss.PutBucketWebsiteRequest{
		Bucket: oss.Ptr(bucketName), // The bucket name.
		WebsiteConfiguration: &oss.WebsiteConfiguration{
			IndexDocument: &oss.IndexDocument{
				Suffix:        oss.Ptr("index.html"), // Set the index page to index.html.
				SupportSubDir: oss.Ptr(true),         // Enable subdirectory support.
				Type:          oss.Ptr(int64(0)),     // Type (0 indicates a static website).
			},
			ErrorDocument: &oss.ErrorDocument{
				Key:        oss.Ptr("error.html"), // Set the error page to error.html.
				HttpStatus: oss.Ptr(int64(404)),   // The HTTP status code.
			},
		},
	}

	// Send the request to configure static website hosting.
	result, err := client.PutBucketWebsite(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put bucket website %v", err)
	}

	// Print the result.
	log.Printf("put bucket website result:%#v\n", result)
}

Interroger

L'exemple ci-dessous récupère la configuration d'hébergement de site web statique d'un bucket. Enregistrez ce fichier sous le nom get_bucket_website.go.

Pour l'exemple exécutable complet, consultez get_bucket_website.go sur GitHub.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // The region where the bucket is located.
	bucketName string // The name of the bucket.
)

// The init function initializes command-line flags.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse the command-line flags.
	flag.Parse()

	// Check if the bucket name is provided.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check if the region is provided.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load default configurations and set the credentials provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to query the static website hosting configuration.
	request := &oss.GetBucketWebsiteRequest{
		Bucket: oss.Ptr(bucketName), // The bucket name.
	}

	// Send the request and process the response.
	result, err := client.GetBucketWebsite(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket website %v", err)
	}

	// Print the query result.
	log.Printf("get bucket website result:%#v\n", result)
}

Supprimer

L'exemple ci-dessous supprime la configuration d'hébergement de site web statique d'un bucket. Enregistrez ce fichier sous le nom delete_bucket_website.go.

Pour l'exemple exécutable complet, consultez delete_bucket_website.go sur GitHub.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // The region where the bucket is located.
	bucketName string // The name of the bucket.
)

// The init function initializes command-line flags.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse the command-line flags.
	flag.Parse()

	// Check if the bucket name is provided.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check if the region is provided.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load default configurations and set the credentials provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to delete the static website hosting configuration.
	request := &oss.DeleteBucketWebsiteRequest{
		Bucket: oss.Ptr(bucketName),
	}

	// Send the request and process the response.
	result, err := client.DeleteBucketWebsite(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete bucket website %v", err)
	}

	// Print the result.
	log.Printf("delete bucket website result:%#v\n", result)
}

Back-to-origin par miroir

Le back-to-origin par miroir est conçu pour faciliter la migration transparente des données vers OSS. Si votre service s'exécute sur une origine gérée en interne ou sur un autre service cloud, vous pouvez migrer vers OSS sans interruption de service. Pendant la migration, OSS utilise des règles de routage pour récupérer les objets depuis l'origine chaque fois qu'un objet demandé n'a pas encore été migré, garantissant ainsi la continuité du service. Cette section couvre les trois opérations suivantes : PutBucketWebsite, GetBucketWebsite et DeleteBucketWebsite.

Configurer

Lorsqu'un client demande un objet qui n'existe pas dans le bucket, OSS peut le récupérer depuis une origine à l'aide d'une règle de routage de back-to-origin. Par exemple, pour un bucket dans la région Chine (Hangzhou) : lorsqu'un client demande un objet manquant dont la clé commence par myobject, la règle de routage le récupère depuis http://www.test.com//@filepath.

L'exemple ci-dessous configure cette règle de routage pour le back-to-origin par miroir. Enregistrez ce fichier sous le nom put_bucket_website.go.

Pour l'exemple exécutable complet, consultez put_bucket_website.go sur GitHub.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // The region where the bucket is located.
	bucketName string // The name of the bucket.
)

// The init function initializes command-line flags.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse the command-line flags.
	flag.Parse()

	// Check if the bucket name is provided.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check if the region is provided.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load default configurations and set the credentials provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Configure a routing rule.
	ruleOk := oss.RoutingRule{
		RuleNumber: oss.Ptr(int64(1)),
		Condition: &oss.RoutingRuleCondition{
			KeyPrefixEquals:             oss.Ptr("myobject"), // Specify the object key prefix for condition matching.
			HttpErrorCodeReturnedEquals: oss.Ptr(int64(404)), // The back-to-origin action is triggered when an HTTP 404 error is returned.
		},
		Redirect: &oss.RoutingRuleRedirect{
			RedirectType: oss.Ptr("Mirror"),               // Set the redirect type to Mirror.
			MirrorURL:    oss.Ptr("http://www.test.com/"), // Specify the back-to-origin URL.
			MirrorHeaders: &oss.MirrorHeaders{
				//PassAll: oss.Ptr(true),                              // Pass all headers.
				Passes:  []string{"myheader-key1", "myheader-key2"}, // Pass the specified HTTP headers.
				Removes: []string{"myheader-key3", "myheader-key4"}, // Do not pass the specified HTTP headers.
				Sets: []oss.MirrorHeadersSet{
					{
						Key:   oss.Ptr("myheader-key5"),  // Set the key for a specific HTTP header.
						Value: oss.Ptr("myheader-value"), // Set the value for a specific HTTP header.
					},
				},
			},
		},
	}

	// Create a request to configure mirroring-based back-to-origin.
	request := &oss.PutBucketWebsiteRequest{
		Bucket: oss.Ptr(bucketName), // The bucket name.
		WebsiteConfiguration: &oss.WebsiteConfiguration{
			IndexDocument: &oss.IndexDocument{
				Suffix:        oss.Ptr("index.html"), // Set the index page to index.html.
				SupportSubDir: oss.Ptr(true),
				Type:          oss.Ptr(int64(0)),
			},
			ErrorDocument: &oss.ErrorDocument{
				Key:        oss.Ptr("error.html"), // Set the error page to error.html.
				HttpStatus: oss.Ptr(int64(404)),
			},
			RoutingRules: &oss.RoutingRules{
				RoutingRules: []oss.RoutingRule{
					ruleOk,
				},
			},
		},
	}

	// Send the request to configure mirroring-based back-to-origin.
	result, err := client.PutBucketWebsite(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put bucket website %v", err)
	}

	// Print the result.
	log.Printf("put bucket website result:%#v\n", result)
}

Interroger

L'exemple ci-dessous récupère la configuration de back-to-origin par miroir d'un bucket. Enregistrez ce fichier sous le nom get_bucket_website.go.

Pour l'exemple exécutable complet, consultez get_bucket_website.go sur GitHub.

Important

Si le bucket ne possède aucune configuration de site web, GetBucketWebsite renvoie une erreur NoSuchWebsiteConfiguration. Ce comportement est attendu lors de l'interrogation d'un bucket qui n'a jamais été configuré. Traitez cette erreur séparément des autres échecs d'API afin d'éviter de masquer des erreurs réelles.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // The region where the bucket is located.
	bucketName string // The name of the bucket.
)

// The init function initializes command-line flags.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse the command-line flags.
	flag.Parse()

	// Check if the bucket name is provided.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check if the region is provided.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load default configurations and set the credentials provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to query the mirroring-based back-to-origin configuration.
	request := &oss.GetBucketWebsiteRequest{
		Bucket: oss.Ptr(bucketName), // The bucket name.
	}

	// Send the request and process the response.
	result, err := client.GetBucketWebsite(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket website %v", err)
	}

	// Print the routing rules from the result.
	log.Printf("get bucket website result:%#v\n", result.WebsiteConfiguration.RoutingRules)
}

Supprimer

L'exemple ci-dessous supprime la configuration de back-to-origin par miroir d'un bucket. Enregistrez ce fichier sous le nom delete_bucket_website.go.

Pour l'exemple exécutable complet, consultez delete_bucket_website.go sur GitHub.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // The region where the bucket is located.
	bucketName string // The name of the bucket.
)

// The init function initializes command-line flags.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse the command-line flags.
	flag.Parse()

	// Check if the bucket name is provided.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check if the region is provided.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load default configurations and set the credentials provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to delete the bucket's website configuration.
	request := &oss.DeleteBucketWebsiteRequest{
		Bucket: oss.Ptr(bucketName),
	}

	// Send the request and process the response.
	result, err := client.DeleteBucketWebsite(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete bucket website %v", err)
	}

	// Print the result.
	log.Printf("delete bucket website result:%#v\n", result)
}

Références