Fix ‘No Access-Control-Allow-Origin header’ errors on Amazon S3 by testing the preflight with curl

by 13 min read
Title card reading: Fix No Access-Control-Allow-Origin header errors on Amazon S3 by testing the preflight with curl
On this page

Your browser blocks a request to an S3 bucket and reports that no Access-Control-Allow-Origin header is present, a CORS (cross-origin resource sharing) error. This post is for developers who call S3 from a web page, with or without CloudFront in front. Copy the browser’s preflight (the OPTIONS request it sends first) into one curl command, read S3’s answer, and make the one fix it points to.

Key takeaways

  • S3 sends CORS headers only when one rule matches the request’s origin, method and every requested header.
  • One curl request that copies the browser’s preflight shows S3’s real answer: 307, 403 with a CORS message, or 200.
  • List the real request’s method in AllowedMethods, such as PUT for an upload, and never OPTIONS.
  • Behind CloudFront, put Origin, Access-Control-Request-Headers and Access-Control-Request-Method in the cache policy, not only the origin request policy.
  • After a fix, invalidate the CloudFront cache if you use it, then run curl again before you reload the browser.

In this post

S3 sends no Access-Control-Allow-Origin header unless one rule matches

Most failing requests are preflighted. For a request that is not simple, such as a PUT upload, the browser first sends an OPTIONS request to the other origin to check that the real request is safe to send (MDN, CORS). That preflight carries Origin, Access-Control-Request-Method and, optionally, Access-Control-Request-Headers, and the browser builds it on its own (MDN, Preflight request).

S3 answers a preflight that matches no rule with 403 Forbidden and a short “CORS Response” text (AWS, Troubleshooting CORS). The browser reports that failure only as a missing header, so curl is the quickest way to read S3’s own answer.

Send the browser’s preflight with curl

Copy the three headers from DevTools

Open your browser’s developer tools, select the Network tab and reload the page. Find the OPTIONS request just before the failed one, and copy three request headers from it: Origin exactly as sent, Access-Control-Request-Method, and Access-Control-Request-Headers if it is there (MDN, Preflight request).

If there is no OPTIONS request, the browser sent a simple request without a preflight. Test that case with a plain GET that carries the same Origin, for example curl -i -H "Origin: https://app.example.com" "https://<BUCKET>.s3.<REGION>.amazonaws.com/<KEY>" against the S3 Regional endpoint.

The command

Send the same headers to the bucket’s Regional endpoint. The header values below are examples: replace them with the ones you copied, and replace <BUCKET>, <REGION> and <KEY> with your bucket name, its Region and an object key. Run them against a test bucket before you change a production one.

Bash
curl -i -X OPTIONS \
  -H "Origin: https://app.example.com" \
  -H "Access-Control-Request-Method: PUT" \
  -H "Access-Control-Request-Headers: content-type" \
  "https://<BUCKET>.s3.<REGION>.amazonaws.com/<KEY>"

AWS documents this test as a preflight OPTIONS check sent with curl (AWS, Testing CORS). Write -X with an uppercase X.

Run it once without Origin, as a control

Browsers always send Origin on a CORS request (MDN, CORS); in curl you add it yourself with -H. Run the command once with the Origin line removed: S3 matches the request’s Origin header against AllowedOrigins (AWS, Using CORS), so expect no CORS headers, even on a correctly configured bucket (confirm this on your test bucket).

A passing answer

A matching preflight gets 200 OK (AWS, Testing CORS) and echoes the allowed origin in Access-Control-Allow-Origin; the lines below are an excerpt of AWS’s sample response, which uses AWS’s example origin http://www.example1.com:

HTTP
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://www.example1.com
Vary: Origin, Access-Control-Request-Headers, Access-Control-Request-Method

Any status other than 200 points to one of the cases in the next section.

Match S3’s answer to one fix

Read the status line and any “CORS Response” text, then find the matching row in the table.

What curl shows What it means Fix
403 Forbidden with “CORS Response: CORS is not enabled for this bucket.” The S3 bucket has no CORS configuration (AWS) Add a configuration (next section)
403 Forbidden with “CORS Response: This CORS request is not allowed.” S3 found rules, but no rule matches the origin, method and headers together (AWS) Edit one rule to match all three
CORS headers from the S3 URL, none (or an old answer) from the CloudFront URL The proxy drops the CORS headers or caches without Origin in the key (AWS) Fix the CloudFront cache behavior
307 Temporary Redirect Legacy global S3 endpoint, bucket in an older Region (AWS) Use the Regional endpoint
200 OK with Access-Control-Allow-Origin, but the browser still blocks A credentialed request answered with * (MDN), or a response header S3 does not expose (AWS) See “The header is present but the browser still blocks the response”

“CORS is not enabled for this bucket”: add a CORS configuration

This answer means the bucket has no CORS configuration at all (AWS, Troubleshooting CORS). The console and the CLI paths below both set the same example rule.

An example rule

The S3 console takes the configuration as JSON (AWS, Elements of a CORS configuration), written as a bare array of rule objects. All values are examples:

JSON
[
  {
    "ID": "browser-app",
    "AllowedOrigins": ["https://app.example.com"],
    "AllowedMethods": ["GET", "PUT", "HEAD"],
    "AllowedHeaders": ["content-type"],
    "ExposeHeaders": ["ETag"],
    "MaxAgeSeconds": 300
  }
]

The AWS CLI needs the same rules inside a top-level CORSRules list (AWS CLI, put-bucket-cors).

Four fields in the rule need care:

  • AllowedOrigins holds the origin your page runs on, copied exactly from the Origin header. An S3 origin entry can contain one * wildcard, such as https://*.example.com, and "*" alone allows every origin (AWS, Elements of a CORS configuration). A named origin is safer, because the browser blocks a request with credentials when the answer is Access-Control-Allow-Origin: * (MDN, CORS).
  • AllowedMethods lists the methods the real request uses. Valid values are GET, PUT, HEAD, POST and DELETE (Boto3, put_bucket_cors), so OPTIONS never goes in the list. S3 matches a preflight by the method in Access-Control-Request-Method (AWS, Using CORS).
  • ExposeHeaders lets JavaScript read response headers such as ETag, which browsers hide by default (AWS, Troubleshooting CORS).
  • A CORS rule grants no access of its own: S3 ACLs and policies still apply when you enable CORS (AWS, Using CORS).

Console steps (Amazon S3)

  1. Open the Amazon S3 console at https://console.aws.amazon.com/s3/. In the left navigation pane, choose General purpose buckets, then choose the name of the bucket.
  2. Choose the Permissions tab.
  3. In the Cross-origin resource sharing (CORS) section, choose Edit.
  4. In the CORS configuration editor, paste the JSON array without the CORSRules wrapper, then choose Save changes.

These labels follow AWS’s guide to configuring CORS in the S3 console (AWS, Configuring CORS). If the editor already holds rules, add yours to the array and keep the others. Run the curl command again after you save.

CLI: read the rules, then replace them

put-bucket-cors replaces the whole S3 CORS configuration when one exists (AWS CLI, put-bucket-cors), so read the current rules first:

Bash
aws s3api get-bucket-cors --bucket <BUCKET>

On a bucket without a configuration, this call fails with the S3 error code NoSuchCORSConfiguration (Boto3 guide, Bucket CORS configuration). Put the existing rules and the new one in cors.json under CORSRules, then write them all back:

Bash
aws s3api put-bucket-cors --bucket <BUCKET> --cors-configuration file://cors.json

The put-bucket-cors command prints nothing when it succeeds (AWS CLI, put-bucket-cors). The get-bucket-cors output uses the same CORSRules shape as the input (AWS CLI, get-bucket-cors), so you can save it with aws s3api get-bucket-cors --bucket <BUCKET> --output json > cors.json, add your rule and send the file back. --output json keeps the file in JSON even when your CLI profile sets another output format.

“This CORS request is not allowed”: make one rule match all three parts

This answer means the bucket has CORS rules, but none of them matches the request. S3 needs one rule that matches the whole request (AWS, Troubleshooting CORS). It uses the first rule that matches (AWS, Using CORS), so one rule for the origin and a second rule for the header do not add up. Check the three parts against a single rule:

  • The Origin value must match an entry in the S3 rule’s AllowedOrigins (AWS, Using CORS). Paste the value from DevTools unchanged.
  • The method in Access-Control-Request-Method must be in the S3 rule’s AllowedMethods (AWS, Using CORS). An upload sent with PUT needs PUT in that list.
  • Every header named in Access-Control-Request-Headers must match an AllowedHeaders entry (AWS CLI, put-bucket-cors). For example, a presigned PUT upload that sends Content-Type needs content-type in AllowedHeaders. Each S3 AllowedHeaders string can contain one * wildcard (AWS, Elements of a CORS configuration).

One header that no rule allows is enough to remove every CORS header from S3’s answer (AWS, Testing CORS). That is why this case and a bucket with no CORS at all look the same in the browser.

Rule order and the browser’s preflight cache

After you edit a rule, run curl first: it shows S3’s current answer, while the page may still use the cached one.

CloudFront drops or caches the CORS headers: fix the cache behavior

Run the command above against the bucket, then run it again against the distribution. If the bucket answers with CORS headers and the distribution does not, the bucket is fine and the cache behavior needs the changes below. The distribution URL is a placeholder:

Bash
curl -i -X OPTIONS \
  -H "Origin: https://app.example.com" \
  -H "Access-Control-Request-Method: PUT" \
  -H "Access-Control-Request-Headers: content-type" \
  "https://<DISTRIBUTION>.cloudfront.net/<KEY>"

Why CloudFront serves one origin’s answer to every origin

By default CloudFront ignores request headers when it caches, and keeps one version of an object whose responses differ only by request headers (AWS, Cache content based on request headers). The managed CachingOptimized cache policy keeps it that way: its cache key includes only the normalized Accept-Encoding header (AWS, Managed cache policies). The first answer for an object, with or without CORS headers, can then go to every origin until it expires.

Why the origin request policy alone does not fix it

CloudFront uses two kinds of policy here. A cache policy sets the cache key, and every header in the key is also sent to S3. An origin request policy only adds values to the request sent to S3; it leaves the key alone (AWS, Control origin requests). The managed CORS-S3Origin origin request policy (ID 88a5eaf4-2fd4-4709-b370-b4c650ea3fcf) forwards the CORS headers an S3 origin needs (AWS, Managed origin request policies), but it leaves the cache key as it is. To cache per origin, AWS says to forward the headers with a cache policy (AWS, Cache content based on request headers).

The cache policy decides what CloudFront caches by, while the origin request policy only changes what S3 receives, so Origin has to be in the cache policy.

If you don’t cache OPTIONS responses, AWS says forwarding Origin with the two Access-Control-Request-* headers is enough for the preflight (AWS, Cache content based on request headers). Cached GET responses from S3 still need Origin in the cache key (AWS, Troubleshooting CORS).

Console steps (CloudFront)

  1. Open the Policies page of the CloudFront console (https://console.aws.amazon.com/cloudfront/v4/home?#/policies) and choose Create cache policy (AWS, Create cache policies).
  2. On the create screen, name the policy and set the TTLs to the values your current policy uses. Under Headers, choose Include the following headers and add Origin, Access-Control-Request-Headers and Access-Control-Request-Method. Choose Create (AWS, Understand cache policies).
  3. Open the Distributions page, choose your distribution, then choose the Behaviors tab (AWS, Create cache policies).
  4. Choose the cache behavior that serves the S3 bucket, then choose Edit.
  5. For Allowed HTTP methods, choose GET, HEAD, OPTIONS. Choose GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE only if uploads go through CloudFront. Under Cached HTTP methods you can also choose to cache OPTIONS responses (AWS, Cache behavior settings).
  6. In the Cache key and origin requests section, choose Cache policy and origin request policy. Set Cache policy to the new policy and Origin request policy to CORS-S3Origin (AWS, Create origin request policies).
  7. Choose Save changes.
  8. Wait until the distribution’s Last modified value changes from Deploying to a date (AWS, Update a distribution).
  9. Open the Invalidations tab, choose Create invalidation, enter the paths one per line (for example /*), and choose Create invalidation (AWS, Invalidate files).

The invalidation makes CloudFront fetch a fresh copy from the origin on the next request (AWS, Invalidate files to remove content), and you can’t cancel it once it starts (AWS, Invalidate files). Run both curl commands again when it finishes.

AWS warns that the wider method lists can let users perform operations you do not want, so restrict access to the S3 bucket (AWS, Cache behavior settings).

A 307 on the preflight: use the Regional endpoint

For a bucket in a Region launched before March 20, 2019, the legacy global endpoint can answer with an HTTP 307 redirect to the correct Region. S3 sends the redirect while it updates the bucket’s DNS record after the bucket is created, which might take time (AWS, Virtual hosting). A redirect breaks the request: MDN lists a 307 Temporary Redirect to a URL on a different origin as not permitted during CORS requests (MDN, CORS request external redirect not allowed), and the Regional host that S3 redirects to is a different origin.

Point the app’s S3 URLs and the SDK client at https://<BUCKET>.s3.<REGION>.amazonaws.com, the standard endpoint format AWS recommends (AWS, Virtual hosting). A change to the CORS rules leaves the redirect in place. Whether your bucket gets a 307 depends on its Region, how recently it was created and the endpoint you use, and the curl test shows which answer you get.

The header is present but the browser still blocks the response

If the request carries a credential, most often a Cookie header, and the response has Access-Control-Allow-Origin: *, the browser blocks access to the response and reports a CORS error in the console (MDN, CORS). List the exact origin in AllowedOrigins instead of *.

If the request succeeds but your JavaScript can’t read ETag or an x-amz-meta-* header, the browser is hiding it: browsers block access to custom response headers by default (AWS, Troubleshooting CORS). Add the header names to ExposeHeaders in the S3 rule. This failure is separate from a missing Access-Control-Allow-Origin header.

Try Opndrive

Opndrive gives any S3-compatible bucket a Drive-like web interface you host yourself.
See it on GitHub or read the docs.

Curious about Opndrive?

Take a look at our FAQ to learn more.

Opndrive

Ready to take control of your S3 storage?

Connect your S3 bucket in minutes and start managing your files with Opndrive's beautiful, modern interface.

Build Opndrive with us

Live demos, reviews on your PRs, and a hand when you get stuck.

Be an early member
Join our Discord