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 equivalem a requisições diretas ao bucket. Também é possível 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 contínua de dados para o Object Storage Service (OSS).
Observações
Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, utilize um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
As credenciais de acesso neste exemplo são obtidas de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso (Python SDK V1).
Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Inicialização.
Para configurar a hospedagem de site estático ou o back-to-origin baseado em espelhamento, é necessária a permissão
oss:PutBucketWebsite. Para consultar a configuração de hospedagem de site estático ou back-to-origin baseado em espelhamento, é necessária a permissãooss:GetBucketWebsite. Para excluir a configuração de hospedagem de site estático ou back-to-origin baseado em espelhamento, é necessária a permissãooss:DeleteBucketWebsite. Para mais informações, consulte Conceder políticas de acesso personalizadas a usuários RAM.
Hospedagem de site estático
-
Configurar hospedagem de site estático
O código de exemplo a seguir mostra como configurar a hospedagem de site estático:
#-*-coding:utf-8-*- import oss2 from oss2.models import BucketWebsite from oss2.credentials import EnvironmentVariableCredentialsProvider # 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. auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) # 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. endpoint = "https://oss-cn-hangzhou.aliyuncs.com" # Specify the region in which the bucket is located. Example: cn-hangzhou This parameter is required if you use the V4 signature algorithm. region = "cn-hangzhou" # Replace examplebucket with the name of the bucket. bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region) # Enable static website hosting, set the default homepage to index.html, and then set the default 404 page to error.html. bucket.put_bucket_website(BucketWebsite('index.html', 'error.html')) -
Consultar configurações de hospedagem de site estático
O exemplo de código abaixo ilustra como consultar as configurações de hospedagem de site estático:
#-*-coding:utf-8-*- import oss2 from oss2.models import BucketWebsite from oss2.credentials import EnvironmentVariableCredentialsProvider # 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. auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) # 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. endpoint = "https://oss-cn-hangzhou.aliyuncs.com" # Specify the region in which the bucket is located. Example: cn-hangzhou This parameter is required if you use the V4 signature algorithm. region = "cn-hangzhou" # Replace examplebucket with the name of the bucket. bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region) try: # If static website hosting is not enabled for the bucket, a NoSuchWebsite exception is thrown when you use get_bucket_website. website = bucket.get_bucket_website() print('Index file is {0}, error file is {1}'.format(website.index_file, website.error_file)) except oss2.exceptions.NoSuchWebsite as e: print('Website is not configured, request_id={0}'.format(e.request_id)) -
Excluir configurações de hospedagem de site estático
Utilize o seguinte código para excluir as configurações de hospedagem de site estático:
#-*-coding:utf-8-*- import oss2 from oss2.models import BucketWebsite from oss2.credentials import EnvironmentVariableCredentialsProvider # 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. auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) # 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. endpoint = "https://oss-cn-hangzhou.aliyuncs.com" # Specify the region in which the bucket is located. Example: cn-hangzhou This parameter is required if you use the V4 signature algorithm. region = "cn-hangzhou" # Replace examplebucket with the name of the bucket. bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region) # Delete the static website hosting configurations. bucket.delete_bucket_website()
Back-to-origin baseado em espelhamento
O back-to-origin baseado em espelhamento é usado principalmente para migrar dados para o OSS sem interrupções. Suponha que seu serviço esteja executando 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 operando durante a transição. Nesse período, use regras de back-to-origin baseado em espelhamento para recuperar dados ainda não migrados para o OSS, assegurando o funcionamento esperado do serviço.
-
Configurar regras de back-to-origin baseado em espelhamento
Quando um solicitante acessa um arquivo inexistente no bucket de destino, especifique condições de back-to-origin e uma URL de origem para buscar o objeto no servidor de origem. Por exemplo, considere um bucket chamado examplebucket na região China (Hangzhou). Se alguém tentar acessar um arquivo ausente no diretório examplefolder, localizado na raiz do bucket, configure o sistema para buscar esse objeto no diretório examplefolder do site https://www.example.com/.
Veja a seguir um exemplo de código para configurar regras de back-to-origin baseado em espelhamento para o cenário descrito:
#-*-coding:utf-8-*- import oss2 from oss2.models import BucketWebsite, MirrorHeadersSet, RedirectMirrorHeaders, Redirect, RoutingRule, \ REDIRECT_TYPE_MIRROR, Condition from oss2.credentials import EnvironmentVariableCredentialsProvider # 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. auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) # 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. endpoint = "https://oss-cn-hangzhou.aliyuncs.com" # Specify the region in which the bucket is located. Example: cn-hangzhou This parameter is required if you use the V4 signature algorithm. region = "cn-hangzhou" # Replace examplebucket with the name of the bucket. bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region) # Enable static website hosting, set the default homepage to index.html, and then set the default 404 page to error.html. index_file = 'index.html' error_file = 'error.html' # Specify the matching conditions. condition1 = Condition(key_prefix_equals='examplefolder', http_err_code_return_equals=404) # Specify the headers that you want to include in the response when the requested object is obtained from the origin. mirror_headers_set_1 = MirrorHeadersSet("myheader-key5", "myheader-value5") mirror_headers_set_2 = MirrorHeadersSet("myheader-key6", "myheader-value6") set_list = [mirror_headers_set_1, mirror_headers_set_2] pass_list = ['myheader-key1', 'myheader-key2'] remove_list = ['myheader-key3', 'myheader-key4'] mirror_header = RedirectMirrorHeaders(pass_all=True, pass_list=pass_list, remove_list=remove_list, set_list=set_list) # Specify the operation that you want to perform when the rule is matched. redirect1 = Redirect(redirect_type=REDIRECT_TYPE_MIRROR, mirror_url='https://www.example.com/', mirror_pass_query_string=True, mirror_follow_redirect=True, mirror_check_md5=True, mirror_headers=mirror_header) rule1 = RoutingRule(rule_num=1, condition=condition1, redirect=redirect1) website_set = BucketWebsite(index_file, error_file, [rule1]) # Configure the mirroring-based back-to-origin rule. bucket.put_bucket_website(website_set) -
Consultar configurações de back-to-origin baseado em espelhamento
Siga este modelo de código para consultar as configurações de back-to-origin baseado em espelhamento:
#-*-coding:utf-8-*- import oss2 from oss2.models import BucketWebsite, MirrorHeadersSet, RedirectMirrorHeaders, Redirect, RoutingRule, \ REDIRECT_TYPE_MIRROR, Condition from oss2.credentials import EnvironmentVariableCredentialsProvider # 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. auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) # 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. endpoint = "https://oss-cn-hangzhou.aliyuncs.com" # Specify the region in which the bucket is located. Example: cn-hangzhou This parameter is required if you use the V4 signature algorithm. region = "cn-hangzhou" # Replace examplebucket with the name of the bucket. bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region) try: # If static website hosting is not enabled for the bucket, a NoSuchWebsite exception is thrown when you use get_bucket_website. website_get = bucket.get_bucket_website() # Query the default homepage. print(website_get.index_file) # Query the default 404 page. print(website_get.error_file) for rule in website_get.rules: print(rule.rule_num) # Query the prefix that is used for rule matching. print(rule.condition.key_prefix_equals) # Query the HTTP status code. print(rule.condition.http_err_code_return_equals) # Query the redirection type. print(rule.redirect.redirect_type) # Query the origin URL for mirroring-based back-to-origin. print(rule.redirect.mirror_url) # Query the parameters in the request. print(rule.redirect.pass_query_string) # Specify the string that is used to replace the object name when the request is redirected. The value of this parameter can be a variable. # print(rule.redirect.replace_key_with) # Specify the string that is used to replace the prefix of the object name when the request is redirected. If the prefix of an object name is empty, the string precedes the object name. # print(rule.redirect.replace_key_prefix_with) # Query the protocol that is used for redirection. # print(rule.redirect.proto) # Query the domain name to which the request is redirected. # print(rule.redirect.host_name) # Query the HTTP status code in the response. # print(rule.redirect.http_redirect_code) except oss2.exceptions.NoSuchWebsite as e: print('Website is not configured, request_id={0}'.format(e.request_id)) -
Excluir configurações de back-to-origin baseado em espelhamento
Para remover as configurações de back-to-origin baseado em espelhamento, execute o código abaixo:
#-*-coding:utf-8-*- import oss2 from oss2.credentials import EnvironmentVariableCredentialsProvider # 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. auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) # 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. endpoint = "https://oss-cn-hangzhou.aliyuncs.com" # Specify the region in which the bucket is located. Example: cn-hangzhou This parameter is required if you use the V4 signature algorithm. region = "cn-hangzhou" # Replace examplebucket with the name of the bucket. bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region) # Delete the mirroring-based back-to-origin configurations. bucket.delete_bucket_website()
Referências
Para detalhes sobre a operação de API usada para configurar hospedagem de site estático ou back-to-origin baseado em espelhamento, consulte PutBucketWebsite.
Saiba mais sobre a operação de API para consultar configurações de hospedagem de site estático ou back-to-origin baseado em espelhamento em GetBucketWebsite.
A operação de API correspondente para excluir configurações de hospedagem de site estático ou back-to-origin baseado em espelhamento está documentada em DeleteBucketWebsite.