All Products
Search
Document Center

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

Last Updated:Dec 22, 2023

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

Usage notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS by using other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about the regions and endpoints supported by OSS, see 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.

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Initialization.

  • To configure static website hosting or mirroring-based back-to-origin, you must have the oss:PutBucketWebsite permission. To query static website hosting configurations or mirroring-based back-to-origin rules, you must have the oss:GetBucketWebsite permission. To delete static website hosting configurations or mirroring-based back-to-origin rules, you must have the oss:DeleteBucketWebsite permission. For more information, see Common examples of RAM policies.

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 sample code provides an example on how to configure static website hosting:

    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. 
        client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
        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)
        }
    }            
  • Query static website hosting configurations

    The following sample code provides an example on how to query static website hosting configurations:

    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. 
        client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
        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)
    }            
  • Delete static website hosting configurations

    The following sample code provides an example on how to delete static website hosting configurations:

    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. 
        client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
        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)
        }
    }            

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 rules

    If a requester attempts to access an object in the specified bucket and 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 the bucket and the object does not exist, the requester is redirected to www.example.com to access the object that is stored in the examplefolder directory of the origin.

    The following sample code provides an example on how to configure mirroring-based back-to-origin rules for the preceding scenario:

    package main
    
    import (
    	"fmt"
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"os"
    )
    
    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. 
    	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    	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)
    	}
    }
    
         
  • Query mirroring-based back-to-origin configurations

    The following sample code provides an example on how to query mirroring-based back-to-origin configurations:

    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. 
        client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
        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)
    }           
  • Delete mirroring-based back-to-origin configurations

    The following sample code provides an example on how to delete mirroring-based back-to-origin configurations:

    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. 
        client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
        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)
        }
    }            

References

  • For the complete sample code that is used to manage static website hosting and mirroring-based back-to-origin, visit GitHub.

  • 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.