Todos os produtos
Search
Central de documentação

Object Storage Service:Hospedagem de site estático (back-to-origin baseado em espelhamento) (SDK para Node.js)

Última atualização: Jul 03, 2026

Configure um bucket para hospedagem de site estático e defina regras de redirecionamento (RoutingRule) para back-to-origin baseado em espelhamento. Após ativar a hospedagem de site estático, as requisições ao site funcionam como requisições diretas ao bucket. Também é possível configurar redirecionamentos automáticos para uma página inicial e uma página de erro específicas. As regras de redirecionamento para back-to-origin baseado em espelhamento facilitam a migração contínua de dados para o Object Storage Service (OSS).

Hospedagem de site estático

Um site estático contém apenas conteúdo estático, incluindo scripts do lado do cliente, como JavaScript. Hospede um site estático em um bucket e acesse-o pelo endpoint do bucket.

  • Configurar hospedagem de site estático

    Configure a hospedagem de site estático:

    const OSS = require('ali-oss')
    
    const client = new OSS({
      // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
      region: 'yourRegion',
      // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
      authorizationV4: true,
      // Set bucket to the name of your bucket.
      bucket: 'yourBucketName',
    });
    
    // Set up static website hosting.
    async function putBucketWebsite () {
      try {
        // Specify the bucket name, for example, examplebucket.    
        const result = await client.putBucketWebsite('examplebucket', {
        // Set the default homepage for static website hosting.
        index: 'index.html',
        // Set the default 404 page for static website hosting.
        error: 'error.html'
      });
       console.log(result);
      } catch (e) {
        console.log(e);
      }
    }
    
    putBucketWebsite();            
  • Visualizar a configuração de hospedagem de site estático

    Visualize a configuração de hospedagem de site estático:

    const OSS = require('ali-oss')
    
    const client = new OSS({
      // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
      region: 'yourRegion',
      // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
      authorizationV4: true,
      // Set bucket to the name of your bucket.
      bucket: 'yourBucketName',
    });
    
    // View the default homepage and default 404 page of the static website hosting configuration.
    async function getBucketWebsite () {
      try {
        // Specify the bucket name, for example, examplebucket.
        const result = await client.getBucketWebsite('examplebucket');
        console.log(result);
      } catch (e) {
        console.log(e);
      }
    }
    
    getBucketWebsite();            
  • Excluir a configuração de hospedagem de site estático

    Exclua a configuração de hospedagem de site estático:

    const OSS = require('ali-oss')
    
    const client = new OSS({
      // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
      region: 'yourRegion',
      // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
      authorizationV4: true,
      // Set bucket to the name of your bucket.
      bucket: 'yourBucketName',
    });
    
    // Delete the static website hosting configuration.
    async function deleteBucketWebsite() {
      try {
        // Specify the bucket name, for example, examplebucket.
        const result = await client.deleteBucketWebsite('examplebucket');
        console.log(result);
      } catch (e) {
        console.log(e);
      }
    }
    
    deleteBucketWebsite();            

Back-to-origin baseado em espelhamento

O back-to-origin baseado em espelhamento serve principalmente para migrar dados para o OSS sem interrupções. Suponha que seu serviço esteja em execução em um servidor de origem próprio ou em outro produto de nuvem. Ao migrar esse serviço para o OSS visando o desenvolvimento de negócios, garanta que ele continue funcionando durante todo o processo. Nesse período, utilize regras de back-to-origin baseado em espelhamento para recuperar dados ainda não migrados para o OSS e assegurar o funcionamento esperado do serviço.

  • Configurar back-to-origin baseado em espelhamento

    Quando um objeto solicitado não existe no bucket, configure regras de back-to-origin para recuperá-lo de um servidor de origem. Por exemplo, se um bucket chamado examplebucket na região China (Hangzhou) receber uma requisição para um objeto inexistente no diretório examplefolder, configure uma regra para buscar esse objeto no diretório examplefolder de https://www.example.com/.

    Configure regras de back-to-origin baseado em espelhamento para este cenário:

    const OSS = require('ali-oss')
    constpath=require("path")
    
    const client = new OSS({
      // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
      region: 'yourRegion',
      // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
      authorizationV4: true,
      // Set bucket to the name of your bucket.
      bucket: 'yourBucketName',
    });
    
    async function putBucketWebsite() {
      try {
        // Specify the bucket name, for example, examplebucket.
        const result = await client.putBucketWebsite("examplebucket", {
          // Set the default homepage for static website hosting.
          index: "index.html",
          // Set the default 404 page for static website hosting.
          error: "error.html",
          // Specify whether to redirect to the default homepage in a subdirectory when a subdirectory is accessed.
          // supportSubDir:true ,
          // After a default homepage is set, specify the behavior for requests for non-existent objects whose names do not end with a forward slash (/). This parameter is active only if SupportSubDir is true.
          // type: 0 ,
          routingRules: [
             { RuleNumber: 1,
                 // The rule applies only to objects with this prefix.
                 Condition: { KeyPrefixEquals: "examplefolder/" ,
                              // Match this rule only if a 404 status code is returned when the specified object is accessed.
                              HttpErrorCodeReturnedEquals: 404
                            },
                 // Specify the redirection type.
                 Redirect: { RedirectType: "Mirror",
                             // Specify whether to include request parameters when a redirection or mirroring-based back-to-origin rule is executed.
                             PassQueryString: true,
                             // Specify the origin URL for mirroring-based back-to-origin.
                             MirrorURL: 'http://example.com/',                         
                             // This has the same effect as PassQueryString but with a higher priority. This parameter is active only if RedirectType is set to Mirror.
                             MirrorPassQueryString:true,
                             // If the back-to-origin request returns a 3xx response, specify whether to follow the redirect to the specified location to fetch data. This parameter is active only if RedirectType is set to Mirror. If set to true, OSS continues to request the address that corresponds to the location.
                             MirrorFollowRedirect:true,
                             // Specify whether to check the MD5 hash of the back-to-origin response body.
                             MirrorCheckMd5:false,
                             // Specify the headers to carry for mirroring-based back-to-origin.
                             // Specify whether to pass through all headers to the origin server.
                             MirrorHeaders:{ PassAll: true,
                                             // Pass the headers specified in Pass to the origin server.
                                             Pass:'myheader-key1',
                                             Pass:'myheader-key2',
                                             // Prohibit the headers specified in Remove from being passed through to the origin server.
                                             Remove:'myheader-key3',
                                             Remove:'myheader-key4'}
                            }}
           ] 
        });
        console.log(result);
      } catch (e) {
        console.log(e);
      }
    }
    
    putBucketWebsite();
  • Obter a configuração de back-to-origin baseado em espelhamento

    Obtenha a configuração de back-to-origin baseado em espelhamento:

    const OSS = require('ali-oss')
    constpath=require("path")
    
    const client = new OSS({
      // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
      region: 'yourRegion',
      // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
      authorizationV4: true,
      // Set bucket to the name of your bucket.
      bucket: 'yourBucketName',
    });
    
    // Get the mirroring-based back-to-origin configuration.
    async function getBucketWebsite () {
      try {
        // Specify the bucket name, for example, examplebucket.
        const result = await client.getBucketWebsite('examplebucket');
        console.log(result);
      } catch (e) {
        console.log(e);
      }
    }
    
    getBucketWebsite();            
  • Excluir a configuração de back-to-origin baseado em espelhamento

    Exclua a configuração de back-to-origin baseado em espelhamento:

    const OSS = require('ali-oss')
    constpath=require("path")
    
    const client = new OSS({
      // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
      region: 'yourRegion',
      // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
      authorizationV4: true,
      // Set bucket to the name of your bucket.
      bucket: 'yourBucketName',
    });
    
    // Delete the mirroring-based back-to-origin configuration.
    async function deleteBucketWebsite() {
      try {
        // Specify the bucket name, for example, examplebucket.
        const result = await client.deleteBucketWebsite('examplebucket');
        console.log(result);
      } catch (e) {
        console.log(e);
      }
    }
    
    deleteBucketWebsite();            

Referências

  • Para obter mais informações sobre a operação de API usada para configurar hospedagem de site estático ou back-to-origin baseado em espelhamento, consulte PutBucketWebsite.

  • Para obter mais detalhes sobre a operação de API usada para obter a configuração de hospedagem de site estático ou back-to-origin baseado em espelhamento, consulte GetBucketWebsite.

  • Para saber mais sobre a operação de API usada para excluir a configuração de hospedagem de site estático ou back-to-origin baseado em espelhamento, consulte DeleteBucketWebsite.