Static website hosting (mirroring-based back-to-origin) (OSS SDK for Go 1.0)

更新时间:
复制 MD 格式

You can configure a bucket for static website hosting and set redirection rules (RoutingRule) for mirroring-based back-to-origin. After you enable static website hosting, requests to the website are equivalent to requests to the bucket. You can also configure automatic redirects to a specified index page and error page. Redirection rules for mirroring-based back-to-origin help you seamlessly migrate data to Object Storage Service (OSS).

Notes

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

  • This topic demonstrates creating an OSSClient instance with an OSS endpoint. For alternative configurations, such as using a custom domain or authenticating with credentials from Security Token Service (STS), see Configure a client (Go SDK V1).

  • To configure static website hosting or mirroring-based back-to-origin, you must have the oss:PutBucketWebsite permission. To retrieve the configuration of static website hosting or mirroring-based back-to-origin, you must have the oss:GetBucketWebsite permission. To delete the configuration of static website hosting or mirroring-based back-to-origin, you must have the oss:DeleteBucketWebsite permission. For more information, see Grant custom access policies to RAM users.

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. 
        // 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)
        }
    }            
  • 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. 
        // 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)
    }            
  • 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. 
        // 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)
        }
    }            

Mirroring-based back-to-origin

Mirroring-based back-to-origin is mainly used for seamless data migration to OSS. For example, your service might be running on your own origin server or on another cloud product. If you want to migrate the service to OSS for business development, you must ensure that the service continues to run during the migration. During the migration, you can use mirroring-based back-to-origin rules to retrieve data that has not been migrated to OSS. This ensures that your service runs as expected.

  • 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"
    	"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)
    	}
    }
        
  • 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. 
        // 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)
    }           
  • 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. 
        // 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)
        }
    }            

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 used to configure static website hosting or mirroring-based back-to-origin, see PutBucketWebsite.

  • For more information about the API operation used to retrieve the configuration of static website hosting or mirroring-based back-to-origin, see GetBucketWebsite.

  • For more information about the API operation used to delete the configuration of static website hosting or mirroring-based back-to-origin, see DeleteBucketWebsite.