Todos los productos
Search
Centro de documentos

Object Storage Service:Hosting de sitios web estáticos (back-to-origin basado en espejo) (OSS SDK for Go 1.0)

Última actualización: Sep 03, 2026

Puede configurar un bucket para el hosting de sitios web estáticos y establecer reglas de redirección (RoutingRule) para el back-to-origin basado en espejo. Una vez habilitado el hosting de sitios web estáticos, las solicitudes al sitio web equivalen a solicitudes al bucket. También puede configurar redirecciones automáticas hacia una página de índice y una página de error específicas. Las reglas de redirección para el back-to-origin basado en espejo le permiten migrar datos a Object Storage Service (OSS) sin interrupciones.

Notas

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Si desea acceder a OSS desde otros servicios de Alibaba Cloud en la misma región que OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y endpoints de OSS, consulte Regions and endpoints.

  • En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para configuraciones alternativas, como el uso de un dominio personalizado o la autenticación con credenciales de Security Token Service (STS), consulte Configure a client (Go SDK V1).

  • Para configurar el hosting de sitios web estáticos o el back-to-origin basado en espejo, debe contar con el permiso oss:PutBucketWebsite. Para recuperar la configuración del hosting de sitios web estáticos o del back-to-origin basado en espejo, debe contar con el permiso oss:GetBucketWebsite. Para eliminar la configuración del hosting de sitios web estáticos o del back-to-origin basado en espejo, debe contar con el permiso oss:DeleteBucketWebsite. Para obtener más información, consulte Grant custom access policies to RAM users.

Hosting de sitios web estáticos

Los sitios web estáticos son aquellos en los que todas las páginas web consisten únicamente en contenido estático, incluidos scripts como código JavaScript que se ejecuta en el cliente. Puede utilizar la función de hosting de sitios web estáticos para alojar su sitio web estático en un bucket de OSS y usar el nombre de dominio del bucket para acceder al sitio.

  • Configurar el hosting de sitios web estáticos

    A continuación se muestra un ejemplo de código para configurar el hosting de sitios web estáticos:

    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)
        }
    }            
  • Consultar configuraciones de hosting de sitios web estáticos

    A continuación se muestra un ejemplo de código para consultar las configuraciones de hosting de sitios web estáticos:

    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)
    }            
  • Eliminar configuraciones de hosting de sitios web estáticos

    A continuación se muestra un ejemplo de código para eliminar las configuraciones de hosting de sitios web estáticos:

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

Back-to-origin basado en espejo

El back-to-origin basado en espejo se utiliza principalmente para la migración de datos a OSS sin interrupciones. Por ejemplo, su servicio podría estar ejecutándose en su propio servidor de origen o en otro producto de nube. Si desea migrar el servicio a OSS para el desarrollo de su negocio, debe asegurarse de que el servicio continúe funcionando durante la migración. Durante este proceso, puede utilizar reglas de back-to-origin basado en espejo para recuperar los datos que aún no se han migrado a OSS. Esto garantiza que su servicio funcione según lo esperado.

  • Configurar reglas de back-to-origin basado en espejo

    Si un solicitante intenta acceder a un objeto en el bucket especificado y el objeto no existe, puede indicar la URL del objeto en el origen y las condiciones de back-to-origin para permitir que el solicitante obtenga el objeto desde el origen. Por ejemplo, suponga que un bucket llamado examplebucket se encuentra en la región China (Hangzhou). Cuando un solicitante intenta acceder a un objeto en el directorio examplefolder del directorio raíz del bucket y el objeto no existe, se redirige al solicitante a www.example.com para acceder al objeto almacenado en el directorio examplefolder del origen.

    A continuación se muestra un ejemplo de código para configurar reglas de back-to-origin basado en espejo para el escenario anterior:

    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)
    	}
    }
        
  • Consultar configuraciones de back-to-origin basado en espejo

    A continuación se muestra un ejemplo de código para consultar las configuraciones de back-to-origin basado en espejo:

    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)
    }           
  • Eliminar configuraciones de back-to-origin basado en espejo

    A continuación se muestra un ejemplo de código para eliminar las configuraciones de back-to-origin basado en espejo:

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

Referencias

  • Para ver el código de ejemplo completo utilizado para gestionar el hosting de sitios web estáticos y el back-to-origin basado en espejo, visite GitHub.

  • Para obtener más información sobre la operación de API utilizada para configurar el hosting de sitios web estáticos o el back-to-origin basado en espejo, consulte PutBucketWebsite.

  • Para obtener más información sobre la operación de API utilizada para recuperar la configuración del hosting de sitios web estáticos o del back-to-origin basado en espejo, consulte GetBucketWebsite.

  • Para obtener más información sobre la operación de API utilizada para eliminar la configuración del hosting de sitios web estáticos o del back-to-origin basado en espejo, consulte DeleteBucketWebsite.