Todos los productos
Search
Centro de documentos

Object Storage Service:Consulta de la región de un bucket

Última actualización: Sep 22, 2026

Si creó una gran cantidad de buckets en diversas regiones, puede especificar el nombre de un bucket para consultar su región. En este tema se describe cómo consultar la región de un bucket al especificar su nombre.

Escenarios

  • Optimización del acceso a los datos: conocer la región donde se ubica su bucket le ayuda a elegir una ruta de acceso óptima. Por ejemplo, si su aplicación se despliega en la misma región que el bucket, configure el acceso mediante la red interna para reducir la latencia y los costos de tráfico.

  • Regiones de almacenamiento de datos por cumplimiento normativo: algunas leyes exigen que los datos se almacenen en regiones específicas para cumplir con ciertos requisitos. En estos casos, sus buckets deben residir en dichas regiones por motivos de cumplimiento.

  • Redundancia de datos entre regiones o recuperación ante desastres: si su aplicación requiere alta disponibilidad, debe almacenar los datos en buckets de distintas regiones para admitir la replicación de datos y la conmutación por error.

Notas de uso

  • Para obtener más información sobre las regiones compatibles con OSS, consulte Regions and endpoints.

  • Por ejemplo, en la región China (Hangzhou), el campo Location de la respuesta es oss-cn-hangzhou.

Métodos

Uso de la consola de OSS

  1. Inicie sesión en la consola de OSS.

  2. En el panel de navegación izquierdo, haga clic en Buckets. En la página Buckets, haga clic en el nombre del bucket.

    La región del bucket se muestra en la esquina superior izquierda de la página que aparece.

Uso de ossbrowser

Con ossbrowser puede ejecutar las mismas operaciones de nivel de bucket que en la consola de OSS. Siga las instrucciones en pantalla de ossbrowser para consultar la región de un bucket. Para obtener más información, consulte 常用操作.

Uso de los SDK de OSS

A continuación se muestran ejemplos de código para consultar la región de un bucket mediante los SDK de OSS en diversos lenguajes de programación. Para obtener más información sobre cómo consultar la región de un bucket con los SDK de OSS en otros lenguajes, consulte 简介.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Specify the endpoint of a region that is supported by OSS. Example: https://oss-cn-hangzhou.aliyuncs.com. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 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. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name. Example: examplebucket. 
        String bucketName = "examplebucket";
        // 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.
        String region = "cn-hangzhou";
        
        // Create an OSS Client instance.
        // Call the shutdown method to release associated resources when the OSS Client is no longer in use.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            String location = ossClient.getBucketLocation(bucketName);
            System.out.println(location);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
const OSS = require('ali-oss');

const client = new OSS({
  // Obtain the access credentials from environment variables. Before you run this code sample, 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,
  // Specify the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, specify oss-cn-hangzhou. Replace the example value with the actual region of your bucket.
  region: 'oss-cn-hangzhou',
  // Use the V4 signature algorithm.
  authorizationV4: true,
  // Specify the name of your bucket.
  bucket: 'yourBucketName',
  // Specify the public endpoint of the region where the bucket resides. For example, if the bucket is in the China (Hangzhou) region, specify https://oss-cn-hangzhou.aliyuncs.com. Replace the example value with the actual endpoint of your bucket.
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
});

async function getLocation() {
  try {
    const result = await client.getBucketInfo();
    console.log(result.bucket.Location);
  } catch (e) {
    console.log(e);
  }
}

getLocation();
using Aliyun.OSS;
using Aliyun.OSS.Common;
// 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. 
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 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. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. 
var bucketName = "yourBucketName";

// Create an OSSClient instance. 
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
    // Query the region of the bucket. 
    var result = client.GetBucketLocation(bucketName);
    Console.WriteLine("Get bucket:{0} Info succeeded ", bucketName);
    Console.WriteLine("bucket Location: {0}", result.Location);
   
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the OSS account information. */
    
    /* Specify the endpoint of any region that OSS supports. For example, https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to cn-hangzhou. */
    std::string Region = "yourRegion";
    
    /* Set yourBucketName to the name of the bucket. */
    std::string BucketName = "yourBucketName";

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* 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. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* Get the region of the bucket. */
    GetBucketLocationRequest request(BucketName);
    auto outcome = client.GetBucketLocation(request);

    if (outcome.isSuccess()) {    
        std::cout << "getBucketLocation success, location: " << outcome.result().Location() << std::endl;
    }
    else {
        /* Handle the exception. */
        std::cout << "getBucketLocation fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        ShutdownSdk();
        return -1;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the endpoint of any OSS region. Example: https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";

/* Specify the bucket name. */
const char *bucket_name = "yourBucket";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Initialize an aos_string_t type with a char* string. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* 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 set. */    
    aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
    aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
    // Configure the following two parameters.
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    /* Specify whether to use a CNAME to access OSS. A value of 0 indicates that a CNAME is not used. */
    options->config->is_cname = 0;
    /* Set network parameters, such as the timeout period. */
    options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
    /* Call the aos_http_io_initialize method at the program entry to initialize global resources such as the network and memory. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* The memory pool (pool) is used for memory management and is equivalent to apr_pool_t. The implementation code is in the apr library. */
    aos_pool_t *pool;
    /* Create a memory pool. The second parameter is NULL, which indicates that the memory pool does not inherit from another memory pool. */
    aos_pool_create(&pool, NULL);
    /* Create and initialize options. The options include global configurations such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
    oss_request_options_t *oss_client_options;
    /* Allocate memory to options in the memory pool. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize the client options oss_client_options. */
    init_options(oss_client_options);
    /* Initialize parameters. */
    aos_string_t bucket;
    aos_string_t oss_location;
    aos_table_t *resp_headers = NULL; 
    aos_status_t *resp_status = NULL; 
    /* Assign the char* data to the aos_string_t bucket. */
    aos_str_set(&bucket, bucket_name);
    /* Get the region of the bucket. */
    resp_status = oss_get_bucket_location(oss_client_options, &bucket, &oss_location, &resp_headers);
    if (aos_status_is_ok(resp_status)) {
        printf("get bucket location succeeded : %s \n", oss_location.data);
    } else {
        printf("get bucket location failed\n");
    }
    /* Release the memory pool. This releases the memory allocated for various resources during the request. */
    aos_pool_destroy(pool);
    /* Release the previously allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}
package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region.
	bucketName string // The name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to query the region of the bucket.
	request := &oss.GetBucketLocationRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
	}

	// Execute the request to query the region of the bucket and process the result.
	result, err := client.GetBucketLocation(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket location %v", err)
	}

	// Display the region of the bucket.
	log.Printf("get bucket location:%#v\n", *result.LocationConstraint)
}
import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser. This script is used to obtain the location information of a specified bucket.
parser = argparse.ArgumentParser(description="Get the location of a specified OSS bucket.")

# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket to get the location for.', required=True)

# Add the --endpoint command-line argument, which specifies the domain names that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS.')

def main():
    """
    The main function, which is used to parse command-line arguments and obtain the location information of the specified bucket.
    """

    args = parser.parse_args()  # Parse command-line arguments.

    # Load credential information from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK, and set the credentials provider and region information.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    # If the endpoint argument is provided, set the endpoint in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSS client using the configured information.
    client = oss.Client(cfg)

    # Construct a request to obtain the location information of the specified bucket.
    request = oss.GetBucketLocationRequest(bucket=args.bucket)

    # Execute the request and obtain the response.
    result = client.get_bucket_location(request)

    # Print the status code, request ID, and location information of the response.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' location: {result.location}'
    )

if __name__ == "__main__":
    main()  # The script entry point. The main function is called when the file is run directly.
<?php

require_once __DIR__ . '/../vendor/autoload.php'; // Introduce autoload files to load dependency libraries.

use AlibabaCloud\Oss\V2 as Oss;

// Define the description of command-line parameters.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region in which the bucket is located is required. For example: oss-cn-hangzhou.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) The endpoint of the region in which the bucket is located. 
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) The name of the bucket.
];
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));

// Parse the command-line parameters.
$options = getopt("", $longopts); 

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Display the required but missing parameters.
        exit(1); 
    }
}

// Obtain the values of the command line parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.

// Use environment variables to load the AccessKey ID and AccessKey secret.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Load access credentials from environment variables.

// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault(); // Load the default configuration of the SDK.
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if one is provided.
}

// Create an OSS client instance.
$client = new Oss\Client($cfg); 

// Create a request to query the region of a bucket.
$request = new Oss\Models\GetBucketLocationRequest($bucket); 

// Call the getBucketLocation method.
$result = $client->getBucketLocation($request); 

// Display the result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code.
    'request id:' . $result->requestId . PHP_EOL . // The unique ID of the request.
    'bucket location:' . var_export($result->location, true) // The region in which the bucket is located.
);

Uso de ossutil

Puede usar ossutil para consultar la región donde se ubica un bucket. Para obtener más información sobre cómo instalar ossutil, consulte Install ossutil.

El siguiente ejemplo de código muestra cómo consultar la región donde se ubica examplebucket.

ossutil api get-bucket-location --bucket examplebucket

Para obtener más información, consulte get-bucket-location.

Operación de API relacionada

Las operaciones descritas anteriormente se implementan fundamentalmente mediante la API RESTful. Puede invocarla directamente si su negocio requiere un alto nivel de personalización. Para invocar una API de forma directa, debe incluir el cálculo de la firma en su código. Para obtener más información, consulte GetBucketLocation.