All Products
Search
Document Center

Object Storage Service:Configure cross-origin resource sharing in OSS

Last Updated:Apr 16, 2025

By default, the same-origin policy restricts cross-origin requests from web browsers and allows JavaScript to access only resources from the same origin. By configuring cross-origin resource sharing (CORS) rules, you can authorize websites to use JavaScript to request non-same-origin OSS object links, which resolves cross-origin issues and enhances the flexibility of resource access.

Same-origin check

The same-origin policy is a key security mechanism used by browsers to isolate potentially malicious files. When a request is sent from Website A by using JavaScript code to access Website B of another origin, the browser rejects the request.

Origins that use the same protocol, domain name or IP address, and port number are considered to be the same origin. The following table provides examples of same-origin checks relative to http://www.aliyun.com/org/test.html:

URL

Access allowed

Reason

http://www.aliyun.com/org/other.html

Yes

Same protocol, domain name, and port number

http://www.aliyun.com/org/internal/page.html

Yes

Same protocol, domain name, and port number

https://www.aliyun.com/page.html

No

Different protocols (HTTP and HTTPS)

http://www.aliyun.com:22/dir/page.html

No

Different port numbers (22 and no port number)

http://www.alibabacloud.com/help/other.html

No

Different domain names

The preceding table shows that the browser rejects requests from a URL to another URL that has a different origin. If you want to allow cross-origin requests, you must configure CORS rules.

Notes

  • You can configure up to 20 CORS rules for each bucket.

  • OSS matches the rules in sequence. After OSS finds the first match, OSS returns corresponding headers. If no match is found, no CORS-related headers are attached.

  • If you enable Alibaba Cloud CDN acceleration and need cross-origin access, you must configure CORS rules in the CDN console.

Cors rules

OSS supports configuring CORS rules to allow or reject cross-origin requests.

CORS rules are configured only to determine whether to add CORS-related headers to requests. The browser determines whether to reject cross-origin requests.

In the following two scenarios, select Return Vary: Origin to prevent local cache confusion.

Important

If you select Return Vary: Origin, the number of browser visits or CDN back-to-origin requests may increase.

  • CORS and non-CORS requests are sent at the same time

    For example, a non-CORS request is sent under the <img> tag, and a CORS request is sent under fetch.

    <!doctype html>
    <html>
    <head>
     <meta charset="UTF-8">
     <title>CORS Test</title>
    </head>
    <body>
    <! -- Non-CORS request -->
    <img src="https://examplebucket.oss-cn-beijing.aliyuncs.com/exampleobject.txt" alt="">
    <script>
      <! -- CORS request -->
     fetch("https://examplebucket.oss-cn-beijing.aliyuncs.com/exampleobject.txt").then(console.log)
    </script>
    </body>
    </html>
  • The Origin header has multiple possible values

    For example, in an actual application, the Origin header of allowed cross-origin requests is set to http://www.example.com and https://www.example.org.

Operations

Use the OSS console

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  3. In the left-side navigation pane, select Content Security > CORS.

  4. On the CORS page, click Create Rule.

  5. In the Create Rule panel, configure the CORS rule based on the following descriptions.

    Parameter

    Required

    Description

    Source

    Yes

    Specifies the origins from which cross-origin requests are allowed. When you configure the sources, take note of the following rules:

    • You can configure multiple sources. Separate multiple sources with line feeds.

    • The domain names must include the protocol name, such as HTTP or HTTPS.

    • You can use an asterisk (*) as the wildcard character in an origin URL. Each origin can contain up to one asterisk (*).

    • If a domain name does not use the default port, the source must contain the port number. For example, https://www.example.com:8080.

    The following examples show how to configure domain names:

    • To match a specific domain name, enter the complete domain name, such as https://www.example.com.

    • To allow requests from subdomains of a specific root domain, use an asterisk (*) wildcard character in an origin URL. For example, https://*.example.com.

    • To allow requests from all origins, enter only an asterisk (*) wildcard character.

    Allowed Methods

    Yes

    The methods that can be used in cross-origin requests.

    Allowed Headers

    No

    The response headers for the allowed cross-origin requests. When you configure the headers, take note of the following rules:

    • The format is key:value, such as content-type:text/plain, which is case-insensitive.

    • You can configure multiple rules for headers. Separate multiple rules with line feeds.

    • You can use an asterisk (*) as a wildcard character. Each header can contain up to one asterisk (*). We recommend that you use an asterisk (*) wildcard character unless otherwise specified.

    Exposed Headers

    No

    The response headers for allowed access requests from applications, such as an XMLHttpRequest object in JavaScript. Exposed headers cannot contain asterisks (*).

    We recommend that you configure the following common exposed headers:

    • x-oss-request-id

      If an issue occurs, provide technical support with the request ID for troubleshooting.

    • ETag

      You can use the ETag value of an object to check whether the object content is modified.

    Cache Timeout (Seconds)

    No

    The period of time in which the browser can cache the response to an OPTIONS preflight request for specific resources. Unit: seconds.

    Vary: Origin

    No

    Specifies whether to return the Vary: Origin Header.

    If CORS and non-CORS requests are sent at the same time in an actual application, or if the Origin header has multiple possible values, we recommend that you select Vary: Origin to prevent local cache confusion.

    Important

    If you select Vary: Origin, the number of browser visits or CDN back-to-origin requests may increase.

  6. Click OK.

Use Alibaba Cloud SDKs

The following code provides examples on how to configure CORS rules by using OSS SDKs for common programming languages. For more information about how to configure CORS rules by using other SDKs, see SDK overview.

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.SetBucketCORSRequest;
import java.util.ArrayList;

public class Demo {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        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 name of the bucket. 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 OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            SetBucketCORSRequest request = new SetBucketCORSRequest(bucketName);

            // You can configure up to 10 CORS rules for a bucket. 
            ArrayList<SetBucketCORSRequest.CORSRule> putCorsRules = new ArrayList<SetBucketCORSRequest.CORSRule>();

            SetBucketCORSRequest.CORSRule corRule = new SetBucketCORSRequest.CORSRule();

            ArrayList<String> allowedOrigin = new ArrayList<String>();
            // Specify the origins from which cross-origin requests are allowed. 
            allowedOrigin.add( "http://example.com");

            ArrayList<String> allowedMethod = new ArrayList<String>();
            // Specify the methods that can be used to send cross-origin requests, including GET, PUT, DELETE, POST, and HEAD. 
            allowedMethod.add("GET");

            ArrayList<String> allowedHeader = new ArrayList<String>();
            // Specify whether the headers that are specified by Access-Control-Request-Headers in the OPTIONS preflight request are allowed. 
            allowedHeader.add("x-oss-test");

            ArrayList<String> exposedHeader = new ArrayList<String>();
            // Specify the response headers for allowed access requests from applications. 
            exposedHeader.add("x-oss-test1");
            // You can use only one asterisk (*) as a wildcard character for AllowedOrigins and AllowedMethods in a CORS rule. The asterisk (*) wildcard character specifies that all origins or operations are allowed. 
            corRule.setAllowedMethods(allowedMethod);
            corRule.setAllowedOrigins(allowedOrigin);
            // AllowedHeaders and ExposeHeaders do not support wildcard characters. 
            corRule.setAllowedHeaders(allowedHeader);
            corRule.setExposeHeaders(exposedHeader);
            // Specify the period of time in which the browser can cache the response for an OPTIONS preflight request for specific resources. Unit: seconds. 
            corRule.setMaxAgeSeconds(10);

            // You can configure up to 10 CORS rules for the bucket. 
            putCorsRules.add(corRule);
            // The existing CORS rules are overwritten. 
            request.setCorsRules(putCorsRules);
            // Specify whether to return the "Vary: Origin" header. If you set this parameter to TRUE, the Vary: Origin header is returned regardless of whether the request is a cross-origin request or whether the cross-origin request is successful. If you set this parameter to False, the Vary: Origin header is not returned. 
            // request.setResponseVary(Boolean.TRUE);
            ossClient.setBucketCORS(request);
        } 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();
            }
        }
    }
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;
use OSS\Model\CorsConfig;
use OSS\Model\CorsRule;

// 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. 
$provider = new 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 name of the bucket. Example: examplebucket. 
$bucket= "examplebucket";

$corsConfig = new CorsConfig();
$rule = new CorsRule();
// Specify the response headers based on which cross-origin requests are allowed. You can specify multiple allowed headers. Only one asterisk (*) can be used as the wildcard character for each allowed header. 
// If you do not have special requirements, we recommend that you set AllowedHeader to an asterisk (*). 
$rule->addAllowedHeader("*");
// Specify the response headers that you are allowed to access from applications. You can specify multiple exposed headers. Exposed headers cannot contain asterisks (*). 
$rule->addExposeHeader("x-oss-header");
// Specify the allowed origins from which cross-origin requests are sent. You can specify multiple allowed origins. Only one asterisk (*) can be used as the wildcard character for each allowed origin. 
$rule->addAllowedOrigin("https://example.com:8080");
$rule->addAllowedOrigin("https://*.aliyun.com");
// If you set AllowedOrigin to an asterisk (*), requests from all origins are allowed. 
//$rule->addAllowedOrigin("*");
// Specify the HTTP methods that cross-origin requests are allowed to use. 
$rule->addAllowedMethod("POST");
// Specify the time that the browser can cache the response to a preflight (OPTIONS) request to a specific resource. Unit: seconds. 
$rule->setMaxAgeSeconds(10);
// You can configure up to 10 CORS rules for each bucket. 
$corsConfig->addRule($rule);
// Specify whether to return the Vary: Origin header. A value of false indicates that the Vary: Origin header is not returned in any case.
$corsConfig->setResponseVary(false);

try{
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

    // OSS overwrites an existing CORS rule that has the same name as the CORS rule that you want to create in the request. 
    $ossClient->putBucketCors($bucket, $corsConfig);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": OK" . "\n");            
const OSS = require('ali-oss');

const client = new OSS({
  // 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 oss-cn-hangzhou. 
  region: 'yourRegion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the name of the bucket. 
  bucket: 'yourBucket'
});

const rules = [{
        // Specify the origin of allowed cross-origin requests. You can set the origin to an asterisk (*) to allow requests from all regions. 
        allowedOrigin: 'http://example.com',
        // Specify the methods that can be used to send cross-origin requests, including GET, PUT, DELETE, POST, and HEAD. 
        allowedMethod: 'GET',
        // Specify the response headers that allow cross-origin requests. We recommend that you use an asterisk (*) as the value, unless otherwise specified. 
        allowedHeader: '*',
        // Specify the response headers for allowed access requests from applications, such as an XMLHttpRequest object in JavaScript. An asterisk (*) is not supported. 
        exposeHeader: 'Content-Length',
        // Specify the period of time in which the browser can cache the response to an OPTIONS preflight request for specific resources. Unit: seconds. 
        maxAgeSeconds: '30'
  },
];
// You can configure up to 10 CORS rules. If a new rule that is the same as an existing rule is configured, the existing rule is overwritten. 
client.putBucketCORS("yourBucket", rules).then((r) => {
  console.log(r);
});           
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import BucketCors, CorsRule

# Obtain access credentials from the environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
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 ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)


rule = CorsRule(allowed_origins=['*'],
                allowed_methods=['GET', 'HEAD'],
                allowed_headers=['*'],
                max_age_seconds=1000)

# An existing rule with the same name is overwritten. 
bucket.put_bucket_cors(BucketCors([rule]))            
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. Example: examplebucket. 
var 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.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();

// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    var request = new SetBucketCorsRequest(bucketName);
    var rule1 = new CORSRule();
    // Specify the origins from which cross-origin requests are allowed. 
    rule1.AddAllowedOrigin("http://example.com");
    // Specify the methods that can be used to send cross-origin requests, including GET, PUT, DELETE, POST, and HEAD. 
    rule1.AddAllowedMethod("POST");
    // AllowedHeaders and ExposeHeaders do not support wildcard characters. 
    rule1.AddAllowedHeader("*");
    // Specify the response headers for allowed access requests from applications. 
    rule1.AddExposeHeader("x-oss-test");
    // You can configure up to 10 CORS rules for a bucket. 
    request.AddCORSRule(rule1);
    var rule2 = new CORSRule();
    // You can use only one asterisk (*) as a wildcard character for AllowedOrigins and AllowedMethods in a CORS rule. The asterisk (*) wildcard character specifies that all origins or operations are allowed. 
    rule2.AddAllowedOrigin("http://example.net");
    rule2.AddAllowedMethod("GET");
    // Specify whether the headers that are specified by Access-Control-Request-Headers in the OPTIONS preflight request are allowed. 
    rule2.AddExposeHeader("x-oss-test2");
    // Specify the period of time in which the browser can cache the response for an OPTIONS preflight request for specific resources. Unit: seconds. 
    rule2.MaxAgeSeconds = 100;
    request.AddCORSRule(rule2);
    // Configure the CORS rules. 
    client.SetBucketCors(request);
    Console.WriteLine("Set bucket:{0} Cors succeeded ", bucketName);
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error info: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error info: {0}", ex.Message);
}
package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Specify the name of the bucket
	bucketName := "yourBucketName"

	// 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.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Error creating credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to 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. Specify your actual endpoint.
	// Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify your actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the signature version
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Error creating OSS client: %v", err)
	}

	isTrue := true
	rule1 := oss.CORSRule{
		AllowedOrigin: []string{"*"},
		AllowedMethod: []string{"PUT", "GET", "POST"},
		AllowedHeader: []string{},
		ExposeHeader:  []string{},
		MaxAgeSeconds: 100,
	}

	rule2 := oss.CORSRule{
		AllowedOrigin: []string{"http://www.a.com", "http://www.b.com"},
		AllowedMethod: []string{"GET"},
		AllowedHeader: []string{"Authorization"},
		ExposeHeader:  []string{"x-oss-test-01", "x-oss-test-02"},
		MaxAgeSeconds: 100,
	}

	put := oss.PutBucketCORS{}
	put.CORSRules = []oss.CORSRule{rule1, rule2}
	put.ResponseVary = &isTrue

	// Configure CORS rules.
	err = client.SetBucketCORSV2(bucketName, put)
	if err != nil {
		log.Fatalf("Error setting CORS rules: %v", err)
	}

	log.Println("Set Success")
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize information about the account that is used to access OSS. */
            
    /* 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. */
    std::string Endpoint = "yourEndpoint";
    /* 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. */
    std::string Region = "yourRegion";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";

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

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

    SetBucketCorsRequest request(BucketName);

    /* Configure CORS rules. */
    auto rule1 = CORSRule();
    /* Specify the origins from which cross-origin requests are allowed. */
    rule1.addAllowedOrigin("http://example.com");
    /* Specify the methods that can be used to send cross-origin requests, including GET, PUT, POST, DELETE, and HEAD. */
    rule1.addAllowedMethod("POST");
    /* Specify whether the headers that are specified by Access-Control-Request-Headers in the OPTIONS preflight request are allowed. */
    rule1.addAllowedHeader("*");
    /* Specify the response headers for allowed access requests from applications. */
    rule1.addExposeHeader("x-oss-test");
    /* You can configure up to 10 CORS rules for the bucket. */
    request.addCORSRule(rule1);

    auto rule2 = CORSRule();
    rule2.addAllowedOrigin("http://example.net");
    rule2.addAllowedMethod("GET");
    rule2.addExposeHeader("x-oss-test2");
    rule2.setMaxAgeSeconds(100);
    request.addCORSRule(rule2);

    auto outcome = client.SetBucketCors(request);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "SetBucketCors fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release resources such as network resources. */
    ShutdownSdk();
    return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* 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. */
const char *endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "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. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Use a char* string to initialize data of the aos_string_t type. */
    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 configured. */
    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"));
    // Specify two additional parameters.
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    /* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
    options->config->is_cname = 0;
    /* Specify 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 in main() to initialize global resources, such as network resources and memory resources. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* Create a memory pool to manage memory. aos_pool_t is equivalent to apr_pool_t. The code used to create a memory pool is included in the APR library. */
    aos_pool_t *pool;
    /* Create a memory pool. The value of the second parameter is NULL. This value indicates that the pool does not inherit other memory pools. */
    aos_pool_create(&pool, NULL);
    /* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
    oss_request_options_t *oss_client_options;
    /* Allocate the memory resources in the memory pool to the options. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize oss_client_options. */
    init_options(oss_client_options);
    /* Initialize the parameters. */
    aos_string_t bucket;
    aos_table_t *resp_headers = NULL; 
    aos_status_t *resp_status = NULL;
    aos_list_t cors_rule_list;
    oss_cors_rule_t *cors_rule1 = NULL, *cors_rule2 = NULL;
    aos_str_set(&bucket, bucket_name);
    aos_list_init(&cors_rule_list);
    cors_rule1 = oss_create_cors_rule(pool);
    aos_list_add_tail(&cors_rule1->node, &cors_rule_list);
    oss_create_sub_cors_rule(pool, &cors_rule1->allowed_origin_list, "allowed_origin_1_1");
    oss_create_sub_cors_rule(pool, &cors_rule1->allowed_origin_list, "allowed_origin_1_1");
    oss_create_sub_cors_rule(pool, &cors_rule1->allowed_method_list, "PUT");
    oss_create_sub_cors_rule(pool, &cors_rule1->allowed_method_list, "GET");
    oss_create_sub_cors_rule(pool, &cors_rule1->allowed_head_list, "Authorization");
    oss_create_sub_cors_rule(pool, &cors_rule1->expose_head_list, "expose_head_1_1");
    oss_create_sub_cors_rule(pool, &cors_rule1->expose_head_list, "expose_head_1_1");
    cors_rule2 = oss_create_cors_rule(pool);
    aos_list_add_tail(&cors_rule2->node, &cors_rule_list);
    oss_create_sub_cors_rule(pool, &cors_rule2->allowed_origin_list, "allowed_origin_2_1");
    oss_create_sub_cors_rule(pool, &cors_rule2->allowed_origin_list, "allowed_origin_2_2");
    oss_create_sub_cors_rule(pool, &cors_rule2->allowed_method_list, "PUT");
    oss_create_sub_cors_rule(pool, &cors_rule2->allowed_method_list, "GET");
    oss_create_sub_cors_rule(pool, &cors_rule2->allowed_head_list, "Authorization");
    oss_create_sub_cors_rule(pool, &cors_rule2->expose_head_list, "expose_head_2_1");
    oss_create_sub_cors_rule(pool, &cors_rule2->expose_head_list, "expose_head_2_2");
    /* Configure CORS rules. */
    resp_status = oss_put_bucket_cors(oss_client_options, &bucket, &cors_rule_list, &resp_headers);
    if (aos_status_is_ok(resp_status)) {
        printf("put bucket cors succeeded\n");
    } else {
        printf("put bucket cors failed\n");      
    }
    /* Release the memory pool. This operation releases the memory resources allocated for the request. */
    aos_pool_destroy(pool);
    /* Release the allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}
require 'aliyun/oss'

client = Aliyun::OSS::Client.new(
  # In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
  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. 
  access_key_id: ENV['OSS_ACCESS_KEY_ID'],
  access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)

# Specify the name of the bucket. Example: examplebucket. 
bucket = client.get_bucket('examplebucket')
# Configure CORS rules. 
bucket.cors = [
    Aliyun::OSS::CORSRule.new(
      # Specify the origin from which you want to allow cross-origin requests. Example: http://example.com. 
      :allowed_origins => ['http://example.com', 'http://example.net'],
      # Specify the methods that can be used to send cross-origin requests, including GET, PUT, DELETE, POST, and HEAD. 
      :allowed_methods => ['PUT', 'POST', 'GET'],
      # Specify the headers that are allowed in OPTIONS preflight requests. Example: x-oss-test. 
      :allowed_headers => ['x-oss-test'],
      # Specify the response headers for allowed access requests from applications. 
      :expose_headers => ['x-oss-test1'],
      # Specify the period of time in which the browser can cache the response for an OPTIONS preflight request for specific resources. Unit: seconds. 
      :max_age_seconds => 100)
]

Use ossutil

You can use the ossutil command-line tool to configure CORS rules. For more information about how to install ossutil, see Install ossutil.

The following command specifies that the allowed origin of cross-origin requests for the bucket named examplebucket is www.aliyun.com, the allowed methods are PUT and GET, and the cache time for the response result is 10000 seconds.

ossutil api put-bucket-cors --bucket examplebucket --cors-configuration  "{\"CORSRule\":{\"AllowedOrigin\":[\"www.aliyun.com\"],\"AllowedMethod\":[\"PUT\",\"GET\"],\"MaxAgeSeconds\":10000}}"

For more information about this command, see put-bucket-cors.

Related API operations

If your business requires a high level of customization, you can directly call the RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see PutBucketCors.

FAQ

The "No 'Access-Control-Allow-Origin'" error

For information about the causes of and solutions to this error, see The "No 'Access-Control-Allow-Origin'" error still occurs when I call OSS after I configure CORS rules.

CORS errors when I use a CDN accelerated domain name to access OSS

If a CORS error occurs when you use a CDN accelerated domain name to access OSS, you must configure CORS rules in the Alibaba Cloud CDN console. For more information, see How do I configure CORS in CDN?.

The "Access-Control-Allow-Origin cannot be an asterisk (*)" error when I send a cross-origin request

If the Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. error occurs, you can modify the value of Access-Control-Allow-Origin in OSS to a specific domain name, or set xhr.withCredentials = false; in your frontend code to resolve this issue. For more information, see The "Access-Control-Allow-Origin cannot be an asterisk (*)" error when I send a cross-origin request.

Why are not all CORS rules effective when I configure two CORS rules?

If you configure two CORS rules, OSS matches the rules in sequence. If OSS finds the first match, OSS returns corresponding headers.