All Products
Search
Document Center

Object Storage Service:Static website hosting (mirroring-based back-to-origin)

Last Updated:Feb 05, 2025

You can enable static website hosting for buckets and configure mirroring-based back-to-origin rules. After you host a static website on a bucket, you can access the bucket to visit the website. You are automatically redirected to the specified index page or error page. After mirroring-based back-to-origin rules are configured and take effect, you can use mirroring-based back-to-origin to seamlessly migrate data to Object Storage Service (OSS).

Notes

  • The sample code in this topic uses the region ID cn-hangzhou of the China (Hangzhou) region. By default, the public endpoint is used to access resources in a bucket. If you want to access resources in the bucket by using other Alibaba Cloud services in the same region in which the bucket is located, use an internal endpoint. For more information about the regions and endpoints supported by Object Storage Service (OSS), see OSS regions and endpoints.

  • In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • The oss:PutBucketWebsite permission is required for static website hosting or mirroring-based back-to-origin configurations. The oss:GetBucketWebsite permission is required to query static website hosting or mirroring-based back-to-origin configurations. The oss:DeleteBucketWebsite permission is required to delete static website hosting or mirroring-based back-to-origin configurations. For more information, see Attach a custom policy to a RAM user.

Static website hosting

Static websites are websites in which all web pages consist only of static content, including scripts such as JavaScript code that can be run on the client. You can use the static website hosting feature to host your static website in an OSS bucket and use the domain name of the bucket to access the website.

Configure static website hosting

The following code provides an example of how to configure static website hosting.

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 // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
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 command line parameters.
	flag.Parse()

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

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

	// Load the default configurations and specify the credential 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), // Name of the bucket.
		WebsiteConfiguration: &oss.WebsiteConfiguration{
			IndexDocument: &oss.IndexDocument{
				Suffix:        oss.Ptr("index.html"), // Set the default homepage to index.html for the static website hosted on the bucket.
				SupportSubDir: oss.Ptr(true),         // Specify that subdirectories are supported.
				Type:          oss.Ptr(int64(0)),     // Type (Setting this parameter to 0 indicates that static website hosting is configured).
			},
			ErrorDocument: &oss.ErrorDocument{
				Key:        oss.Ptr("error.html"), // Set the error page to error.html.
				HttpStatus: oss.Ptr(int64(404)),   // HTTP status code.
			},
		},
	}

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

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

Query static website hosting configurations

The following code provides an example of how to query the static website hosting configurations.

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 // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
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 command line parameters.
	flag.Parse()

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

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

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

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

	// Create a request to query static website hosting configurations for the bucket.
	request := &oss.GetBucketWebsiteRequest{
		Bucket: oss.Ptr(bucketName), // Name of the bucket.
	}

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

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

Delete static website hosting configurations

Below is a sample code snippet for deleting static website hosting configurations:

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 // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
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 command line parameters.
	flag.Parse()

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

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

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

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

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

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

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

Mirroring-based back-to-origin

Mirroring-based back-to-origin allows you to seamlessly migrate data to OSS. For example, you can migrate services from a self-managed origin or from another cloud service to OSS without causing a service interruption. You can use mirroring-based back-to-origin rules during migration to obtain data that is not migrated to OSS. This ensures business continuity.

Configure mirroring-based back-to-origin

If a requester attempts to access an object in a specified bucket but the object does not exist, you can specify the URL of the object in the origin and back-to-origin conditions to allow the requester to obtain the object from the origin. For example, a bucket named examplebucket is located in the China (Hangzhou) region. When a requester attempts to access an object in the examplefolder directory of the root directory of examplebucket located in the China (Hangzhou) region, but the object does not exist, the requester is redirected to its origin www.example.com to access the required object that is stored in the examplefolder directory of the origin.

The following code provides an example of how to configure mirroring-based back-to-origin for the preceding scenario.

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 // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
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 command line parameters.
	flag.Parse()

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

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

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

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

	// Configure mirroring-based back-to-origin rules.
	ruleOk := oss.RoutingRule{
		RuleNumber: oss.Ptr(int64(1)),
		Condition: &oss.RoutingRuleCondition{
			KeyPrefixEquals:             oss.Ptr("myobject"), // Specify the prefix of the object to match.
			HttpErrorCodeReturnedEquals: oss.Ptr(int64(404)), // Set the back-to-origin condition to HTTP status code 404.
		},
		Redirect: &oss.RoutingRuleRedirect{
			RedirectType: oss.Ptr("Mirror"),               // Set the back-to-origin type to mirroring.
			MirrorURL:    oss.Ptr("http://www.test.com/"), // Specify the back-to-origin URL for a mirroring-based back-to-origin rule.
			MirrorHeaders: &oss.MirrorHeaders{
				//PassAll: oss.Ptr(true),                              // Specify that all headers are transmitted.
				Passs:   []string{"myheader-key1", "myheader-key2"}, // Transmit specific HTTP headers.
				Removes: []string{"myheader-key3", "myheader-key4"}, // Prohibit the transmission of specific HTTP headers.
				Sets: []oss.MirrorHeadersSet{
					{
						Key:   oss.Ptr("myheader-key5"),  // Specify the name of the HTTP header.
						Value: oss.Ptr("myheader-value"), // Specify the value of the HTTP header.
					},
				},
			},
		},
	}

	// Create a request to configure mirroring-based back-to-origin rules.
	request := &oss.PutBucketWebsiteRequest{
		Bucket: oss.Ptr(bucketName), // Name of the bucket.
		WebsiteConfiguration: &oss.WebsiteConfiguration{
			IndexDocument: &oss.IndexDocument{
				Suffix:        oss.Ptr("index.html"), // Set the default homepage 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,
				},
			},
		},
	}

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

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

Query mirroring-based back-to-origin configurations

The following code provides an example of how to query the mirroring-based back-to-origin configurations of a bucket.

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 // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
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 command line parameters.
	flag.Parse()

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

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

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

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

	// Create a request to query mirroring-based back-to-origin configurations for the bucket.
	request := &oss.GetBucketWebsiteRequest{
		Bucket: oss.Ptr(bucketName), // Name of the bucket.
	}

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

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

Delete mirroring-based back-to-origin configurations

The following code provides an example of how to delete the mirroring-based back-to-origin configurations of a bucket.

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 // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
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 command line parameters.
	flag.Parse()

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

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

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

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

	// Create a request to delete mirroring-based back-to-origin configurations for the bucket.
	request := &oss.DeleteBucketWebsiteRequest{
		Bucket: oss.Ptr(bucketName),
	}

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

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

References

  • For the complete sample code that is used to configure static website hosting and mirroring-based back-to-origin, visit put_bucket_website.go, get_bucket_website.go, and delete_bucket_website.go.

  • For more information about the API operation that you can call to configure static website hosting or mirroring-based back-to-origin, see PutBucketWebsite.

  • For more information about the API operation that you can call to query static website hosting configurations or mirroring-based back-to-origin rules, see GetBucketWebsite.

  • For more information about the API operation that you can call to delete static website hosting configurations or mirroring-based back-to-origin rules, see DeleteBucketWebsite.