Você pode configurar um bucket para hospedagem de site estático e definir 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 equivalem às requisições ao bucket. Você também pode configurar redirecionamentos automáticos para uma página de índice e uma página de erro específicas. As regras de redirecionamento para back-to-origin baseado em espelhamento facilitam a migração transparente 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. Você pode hospedar um site estático em um bucket e acessá-lo pelo endpoint do bucket.
-
Configurar a 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 é usado principalmente para a migração transparente de dados para o OSS. Por exemplo, seu service pode estar em execução no seu próprio servidor de origem ou em outro cloud product. Ao migrar o service para o OSS para desenvolvimento de negócios, é preciso garantir que o service continue em execução durante a migração. Durante esse processo, use regras de back-to-origin baseado em espelhamento para recuperar dados que ainda não foram migrados para o OSS. Isso garante que seu service funcione conforme o esperado.
-
Configurar o back-to-origin baseado em espelhamento
Quando um objeto requisitado não existe no bucket, você pode configurar regras de back-to-origin para recuperá-lo de um servidor de origem. Por exemplo, se o bucket examplebucket na região China (Hangzhou) receber uma requisição para um objeto inexistente no diretório examplefolder, configure uma regra para buscar o 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 a hospedagem de site estático ou o back-to-origin baseado em espelhamento, consulte PutBucketWebsite.
Para obter mais informações 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 obter mais informações 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.