All Products
Search
Document Center

Object Storage Service:Static website hosting (mirroring back-to-origin) (Go SDK V2)

Last Updated:Jun 04, 2026

Configure a bucket for static website hosting and set up mirroring-based back-to-origin routing rules. Once enabled, OSS serves static content directly from the bucket and redirects requests to the configured index and error pages.

Usage notes

  • The code examples in this topic use the region ID cn-hangzhou, which corresponds to the China (Hangzhou) region. By default, a public endpoint is used. To access OSS from other Alibaba Cloud services within the same region, use an internal endpoint instead. For a full list of supported regions and endpoints, see Regions and endpoints.

  • The examples read access credentials from environment variables. For setup instructions, see Configure access credentials.

  • The following Resource Access Management (RAM) permissions are required:

    • oss:PutBucketWebsite: required to configure static website hosting or mirroring-based back-to-origin.

    • oss:GetBucketWebsite: required to query static website hosting or mirroring-based back-to-origin configurations.

    • oss:DeleteBucketWebsite: required to delete static website hosting or mirroring-based back-to-origin configurations.

    For instructions on granting these permissions, see Attach a policy to a RAM user.

Static website hosting

A static website serves fixed content—HTML pages, images, CSS, and client-side scripts—without server-side processing. All three operations (PutBucketWebsite, GetBucketWebsite, DeleteBucketWebsite) are covered in this section.

Configure

The example below configures a bucket for static website hosting. It sets index.html as the index page and error.html as the 404 error page. Save this as put_bucket_website.go.

For the complete runnable sample, see put_bucket_website.go on 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)
}

Query

The example below retrieves the static website hosting configuration for a bucket. Save this as get_bucket_website.go.

For the complete runnable sample, see get_bucket_website.go on 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)
}

Delete

The example below removes the static website hosting configuration from a bucket. Save this as delete_bucket_website.go.

For the complete runnable sample, see delete_bucket_website.go on 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)
}

Mirroring back-to-origin

Mirroring-based back-to-origin is designed for seamless data migration to OSS. If your service is running on a self-managed origin or another cloud service, you can migrate to OSS without any downtime. During the migration, OSS uses routing rules to fetch objects from the origin whenever a requested object has not yet been migrated—keeping your service running without gaps. All three operations (PutBucketWebsite, GetBucketWebsite, DeleteBucketWebsite) are covered in this section.

Configure

When a client requests an object that does not exist in the bucket, OSS can fetch it from an origin using a back-to-origin routing rule. For example, for a bucket in the China (Hangzhou) region: when a client requests a missing object whose key starts with myobject, the routing rule fetches it from http://www.test.com/.

The example below configures this routing rule for mirroring-based back-to-origin. Save this as put_bucket_website.go.

For the complete runnable sample, see put_bucket_website.go on 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)
}

Query

The example below retrieves the mirroring-based back-to-origin configuration for a bucket. Save this as get_bucket_website.go.

For the complete runnable sample, see get_bucket_website.go on GitHub.

Important

If the bucket has no website configuration, GetBucketWebsite returns a NoSuchWebsiteConfiguration error. This is expected when querying a bucket that has never been configured. Handle this error separately from other API failures to avoid masking genuine errors.

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)
}

Delete

The example below removes the mirroring-based back-to-origin configuration from a bucket. Save this as delete_bucket_website.go.

For the complete runnable sample, see delete_bucket_website.go on 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)
}

References