All Products
Search
Document Center

Object Storage Service:Cross-origin resource sharing (Ruby SDK)

Last Updated:Mar 20, 2026

Browsers enforce the same-origin policy, which blocks requests from one domain to a different domain. Configure cross-origin resource sharing (CORS) rules on your bucket to control which origins, HTTP methods, and headers are allowed for cross-origin requests.

Set CORS rules

Assign an array of Aliyun::OSS::CORSRule objects to bucket.cors. Each rule specifies the allowed origins, HTTP methods, headers, and how long browsers should cache preflight responses.

require 'aliyun/oss'

client = Aliyun::OSS::Client.new(
  # Replace with the endpoint for your region.
  # Example: https://oss-cn-hangzhou.aliyuncs.com for China (Hangzhou).
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
  # Load credentials from environment variables to avoid hardcoding secrets.
  access_key_id: ENV['OSS_ACCESS_KEY_ID'],
  access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)

bucket = client.get_bucket('examplebucket')

bucket.cors = [
  Aliyun::OSS::CORSRule.new(
    :allowed_origins => ['http://example.com', 'http://example.net'],
    :allowed_methods => ['PUT', 'POST', 'GET'],
    :allowed_headers => ['x-oss-test'],
    :expose_headers  => ['x-oss-test1'],
    :max_age_seconds => 100
  )
]

The following table describes each parameter in CORSRule:

ParameterDescriptionExample
:allowed_originsOrigins allowed to make cross-origin requests. Use * to allow all origins.['http://example.com']
:allowed_methodsHTTP methods allowed for cross-origin requests. Supported values: GET, PUT, POST, DELETE, HEAD.['PUT', 'POST', 'GET']
:allowed_headersHeaders allowed in OPTIONS preflight requests. Use * to allow all headers.['x-oss-test']
:expose_headersResponse headers that browsers are allowed to read from applications.['x-oss-test1']
:max_age_secondsCache duration for the OPTIONS preflight response, in seconds.100

Get CORS rules

Read bucket.cors to retrieve the current CORS rules. The property returns an array of CORSRule objects.

require 'aliyun/oss'

client = Aliyun::OSS::Client.new(
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
  access_key_id: ENV['OSS_ACCESS_KEY_ID'],
  access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)

bucket = client.get_bucket('examplebucket')

cors = bucket.cors
puts cors.map(&:to_s)

Delete CORS rules

To remove all CORS rules from a bucket, assign an empty array to bucket.cors.

require 'aliyun/oss'

client = Aliyun::OSS::Client.new(
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
  access_key_id: ENV['OSS_ACCESS_KEY_ID'],
  access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)

bucket = client.get_bucket('examplebucket')

bucket.cors = []

API reference