Tous les produits
Search
Centre de documentation

Object Storage Service:Hébergement de site web statique (récupération par miroir) (SDK Python V1)

Dernière mise à jour :Aug 18, 2026

Vous pouvez configurer un bucket pour l'hébergement de site web statique et définir des règles de redirection (RoutingRule) pour la récupération par miroir. Une fois l'hébergement activé, les requêtes adressées au site sont traitées comme des requêtes adressées au bucket. Vous pouvez également configurer des redirections automatiques vers une page d'index et une page d'erreur spécifiques. Les règles de redirection pour la récupération par miroir facilitent la migration transparente de vos données vers Object Storage Service (OSS).

Notes

  • Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Si vous souhaitez accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un point de terminaison interne. Pour plus d'informations sur les régions et les points de terminaison OSS, consultez Régions et points de terminaison.

  • Les identifiants d'accès utilisés dans cette rubrique proviennent des variables d'environnement. Pour savoir comment les configurer, consultez Configurer les identifiants d'accès à l'aide du SDK OSS pour Python 1.0.

  • Cette rubrique explique comment créer une instance OSSClient avec un endpoint OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Initialisation.

  • Pour configurer l'hébergement de site web statique ou la récupération par miroir, vous devez disposer de l'autorisation oss:PutBucketWebsite. Pour récupérer la configuration, vous avez besoin de l'autorisation oss:GetBucketWebsite. Pour supprimer la configuration, l'autorisation oss:DeleteBucketWebsite est requise. Pour plus d'informations, consultez Accorder des politiques d'accès personnalisées aux utilisateurs RAM.

Hébergement de site web statique

  • Configuration de l'hébergement de site web statique

    L'exemple de code suivant montre comment configurer l'hébergement de site web statique :

    #-*-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'))           
  • Interrogation des configurations d'hébergement de site web statique

    L'exemple de code suivant montre comment interroger les configurations d'hébergement de site web statique :

    #-*-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))           
  • Suppression des configurations d'hébergement de site web statique

    L'exemple de code suivant montre comment supprimer les configurations d'hébergement de site web statique :

    #-*-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()           

Récupération par miroir

La récupération par miroir sert principalement à migrer les données vers OSS en toute transparence. Par exemple, votre service peut s'exécuter sur votre propre serveur d'origine ou sur un autre produit cloud. Si vous souhaitez migrer ce service vers OSS pour développer votre activité, vous devez garantir sa continuité pendant la migration. Durant celle-ci, utilisez des règles de récupération par miroir pour obtenir les données non encore migrées vers OSS. Cela assure le bon fonctionnement de votre service.

  • Configuration des règles de récupération par miroir

    Par exemple, lorsqu'un utilisateur accède à un fichier inexistant dans le bucket de destination, vous pouvez spécifier des conditions de récupération et une URL d'origine pour obtenir le fichier objet depuis le serveur d'origine. Supposons que vous disposiez d'un bucket nommé examplebucket dans la région Chine (Hangzhou). Si un utilisateur tente d'accéder à un fichier inexistant dans le répertoire examplefolder à la racine du bucket, vous souhaitez qu'il puisse récupérer le fichier objet depuis le répertoire examplefolder du site https://www.example.com/.

    L'exemple de code suivant montre comment configurer les règles de récupération par miroir pour le scénario décrit ci-dessus :

    #-*-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)
  • Interrogation des configurations de récupération par miroir

    L'exemple de code suivant montre comment interroger les configurations de récupération par miroir :

    #-*-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))
  • Suppression des configurations de récupération par miroir

    L'exemple de code suivant montre comment supprimer les configurations de récupération par miroir :

    #-*-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()           

Références

  • Pour plus d'informations sur l'opération API permettant de configurer l'hébergement de site web statique ou la récupération par miroir, consultez PutBucketWebsite.

  • Pour plus d'informations sur l'opération API permettant d'interroger les configurations d'hébergement de site web statique ou de récupération par miroir, consultez GetBucketWebsite.

  • Pour plus d'informations sur l'opération API permettant de supprimer les configurations d'hébergement de site web statique ou de récupération par miroir, consultez DeleteBucketWebsite.