Todos os produtos
Search
Central de documentação

Object Storage Service:Consultar a região de um bucket

Última atualização: Jul 03, 2026

Se você criou muitos buckets em diferentes regiões, especifique o nome do bucket para consultar a região correspondente. Este tópico descreve como consultar a região de um bucket informando o respectivo nome.

Cenários

  • Otimização de acesso a dados: saber a região onde seu bucket está localizado ajuda a escolher o melhor caminho de acesso aos dados. Por exemplo, se sua aplicação estiver implantada na mesma região do bucket, configure o acesso pela rede interna para reduzir a latência e os custos de tráfego.

  • Conformidade no armazenamento de dados: algumas leis exigem que os dados sejam armazenados em regiões específicas para atender a requisitos de conformidade. Nesse caso, seus buckets devem residir nessas regiões determinadas.

  • Redundância de dados entre regiões ou recuperação de desastres: caso sua aplicação exija alta disponibilidade, armazene dados em buckets distribuídos por várias regiões para viabilizar a replicação de dados e o failover.

Observações de uso

  • Para obter mais informações sobre as regiões suportadas pelo OSS, consulte Regiões e endpoints.

  • Por exemplo, na região China (Hangzhou), o campo Location na resposta é oss-cn-hangzhou.

Métodos

Usar o console do OSS

  1. Faça login no console do OSS.

  2. No painel de navegação à esquerda, clique em Buckets. Na página Buckets, clique em o nome do bucket desejado.

    A região do bucket aparece no canto superior esquerdo da página exibida.

Usar a ferramenta gráfica de gerenciamento ossbrowser

As operações no nível de bucket suportadas pelo ossbrowser são semelhantes às disponíveis no console. Siga as instruções da interface do ossbrowser para obter as informações de região do bucket. Para mais detalhes sobre como operar o ossbrowser, consulte Operações comuns.

Usar o ossbrowser

Com o ossbrowser, você executa as mesmas operações no nível de bucket disponíveis no console do OSS. Siga as instruções na tela do ossbrowser para consultar a região de um bucket. Para mais informações, consulte Operações comuns.

Usar SDKs do OSS

Os exemplos de código a seguir mostram como consultar a região de um bucket usando os SDKs do OSS nas linguagens de programação mais comuns. Para consultar a região de um bucket com SDKs do OSS em outras linguagens, consulte Visão geral.

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({
    // Get access credentials from environment variables. Before running this 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,
    // Set yourRegion 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: 'oss-cn-hangzhou',
    // Use the V4 signature algorithm.
    authorizationV4: true,
    // Set yourBucketName to the name of the bucket.
    bucket: 'yourBucketName',
    // Set yourEndpoint to the public endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
    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.
);

Usar o ossutil

Use o ossutil para consultar a região onde um bucket está localizado. Para saber como instalar o ossutil, consulte Instalar o ossutil.

O exemplo de código abaixo demonstra como consultar a região onde o bucket examplebucket está localizado.

ossutil api get-bucket-location --bucket examplebucket

Para mais detalhes, consulte get-bucket-location.

Operação de API relacionada

As operações descritas acima são implementadas fundamentalmente com base na API RESTful, que pode ser chamada diretamente caso seu negócio exija alto nível de personalização. Para chamar uma API diretamente, inclua o cálculo da assinatura no seu código. Para mais informações, consulte GetBucketLocation.