Cross origin resource sharing error missing allow origin header

The response to the CORS request is missing the required Access-Control-Allow-Origin header, which is used to determine whether or not the resource can be accessed by content operating within the current origin.

The response to the CORS request is missing the required
Access-Control-Allow-Origin header, which is used to determine whether
or not the resource can be accessed by content operating within the current origin.

If the server is under your control, add the origin of the requesting site to the set
of domains permitted access by adding it to the Access-Control-Allow-Origin
header’s value.

For example, to allow a site at https://amazing.site to access the resource using CORS,
the header should be:

Access-Control-Allow-Origin: https://amazing.site

You can also configure a site to allow any site to access it by using the
* wildcard. You should only use this for public APIs. Private APIs should
never use *, and should instead have a specific domain or domains set. In
addition, the wildcard only works for requests made with the
crossorigin attribute set to anonymous, and it prevents
sending credentials like cookies in requests.

Access-Control-Allow-Origin: *

Warning: Using the wildcard to allow all sites to access a private
API is a bad idea.

To allow any site to make CORS requests without using the *
wildcard (for example, to enable credentials), your server must read the value of the
request’s Origin header and use that value to set
Access-Control-Allow-Origin, and must also set a Vary: Origin
header to indicate that some headers are being set dynamically depending on the origin.

The exact directive for setting headers depends on your web server. In Apache, add a
line such as the following to the server’s configuration (within the appropriate
<Directory>, <Location>,
<Files>, or <VirtualHost> section). The
configuration is typically found in a .conf file (httpd.conf
and apache.conf are common names for these), or in an
.htaccess file.

Header set Access-Control-Allow-Origin 'origin-list'

For Nginx, the command to set up this header is:

add_header 'Access-Control-Allow-Origin' 'origin-list';

This happens generally when you try access another domain’s resources.

This is a security feature for avoiding everyone freely accessing any resources of that domain (which can be accessed for example to have an exact same copy of your website on a pirate domain).

The header of the response, even if it’s 200OK do not allow other origins (domains, port) to access the resources.

You can fix this problem if you are the owner of both domains:

Solution 1: via .htaccess

To change that, you can write this in the .htaccess of the requested domain file:

    <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    </IfModule>

If you only want to give access to one domain, the .htaccess should look like this:

    <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin 'https://my-domain.example'
    </IfModule>

Solution 2: set headers the correct way

If you set this into the response header of the requested file, you will allow everyone to access the resources:

Access-Control-Allow-Origin : *

OR

Access-Control-Allow-Origin : http://www.my-domain.example

Errors: CORSMissingAllowOrigin

Причина:CORS-заголовок ‘Access-Control-Allow-Origin’ отсутствует

Reason

Что пошло не так?

В ответе на запрос CORS отсутствует требуемый заголовок Access-Control-Allow-Origin , который используется для определения того, доступен ли ресурс для контента, работающего в текущем источнике.

Если сервер находится под вашим контролем, добавьте источник запрашивающего сайта в набор доменов, которым разрешен доступ, добавив его к значению заголовка Access-Control-Allow-Origin .

Например, чтобы разрешить сайту https://amazing.site доступ к ресурсу с помощью CORS, заголовок должен быть таким:

Access-Control-Allow-Origin: https://amazing.site

Вы также можете настроить сайт так, чтобы любой сайт мог получить к нему доступ, используя подстановочный знак * . Вы должны использовать это только для общедоступных API. Частные API никогда не должны использовать * , а вместо этого должны иметь определенный домен или домены. Кроме того, подстановочный знак работает только для запросов, сделанных с атрибутом crossorigin , установленным на anonymous , и предотвращает отправку учетных данных, таких как файлы cookie, в запросах.

Access-Control-Allow-Origin: *

Предупреждение: использование подстановочного знака для разрешения всем сайтам доступа к частному API — плохая идея.

Чтобы разрешить любому сайту делать запросы CORS без использования подстановочного знака * (например, для включения учетных данных), ваш сервер должен прочитать значение заголовка Origin запроса и использовать это значение для установки Access-Control-Allow-Origin , а также должен установите заголовок Vary: Origin чтобы указать, что некоторые заголовки устанавливаются динамически в зависимости от источника.

Точная директива для установки заголовков зависит от вашего веб-сервера. В Apache добавьте следующую строку в конфигурацию сервера (в соответствующем разделе <Directory> , <Location> , <Files> или <VirtualHost> ). Конфигурация обычно находится в файле .conf ( обычно для них используются httpd.conf и apache.conf ) или в файле .htaccess .

Header set Access-Control-Allow-Origin 'origin-list'

Для Nginx это команда установки этого заголовка:

add_header 'Access-Control-Allow-Origin' 'origin-list';

See also

  • CORS errors
  • Glossary: CORS
  • CORS introduction


HTTP

  • Errors: CORSMIssingAllowCredentials

    Запрос CORS требует, чтобы сервер разрешал использование учетных данных, но для значения заголовка сервера Access-Control-Allow-Credentials не установлено значение true enable

  • Errors: CORSMissingAllowHeaderFromPreflight

    Access-Control-Allow-Headers отправляется сервером,чтобы сообщить клиенту,что он поддерживает CORS-запросы.

  • Errors: CORSMultipleAllowOriginNotAllowed

    Сервером было отправлено более одного заголовка Access-Control-Allow-Origin.

  • Errors: CORSNotSupportingCredentials

    Запрос CORS был предпринят с установленным флагом учетных данных, но сервер настроен с использованием подстановочного значения Access-Control-Allow-Origin, которое не использует

Cross-Origin Resource Sharing (CORS) is a mechanism that browsers and webviews — like the ones powering Capacitor and Cordova — use to restrict HTTP and HTTPS requests made from scripts to resources in a different origin for security reasons, mainly to protect your user’s data and prevent attacks that would compromise your app.

In order to know if an external origin supports CORS, the server has to send some special headers for the browser to allow the requests.

An origin is the combination of the protocol, domain, and port from which your Ionic app or the external resource is served. For example, apps running in Capacitor have capacitor://localhost (iOS) or http://localhost (Android) as their origin.

When the origin where your app is served (e.g. http://localhost:8100 with ionic serve) and the origin of the resource being requested (e.g. https://api.example.com) don’t match, the browser’s Same Origin Policy takes effect and CORS is required for the request to be made.

CORS errors are common in web apps when a cross-origin request is made but the server doesn’t return the required headers in the response (is not CORS-enabled):

note

XMLHttpRequest cannot load https://api.example.com. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:8100’ is therefore not allowed access.

Request with preflight

By default, when a web app tries to make a cross-origin request the browser sends a preflight request before the actual request. This preflight request is needed in order to know if the external resource supports CORS and if the actual request can be sent safely, since it may impact user data.

A preflight request is sent by the browser if:

  • The method is:
    • PUT
    • DELETE
    • CONNECT
    • OPTIONS
    • TRACE
    • PATCH
  • Or if it has a header other than:
    • Accept
    • Accept-Language
    • Content-Language
    • Content-Type
    • DPR
    • Downlink
    • Save-Data
    • Viewport-Width
    • Width
  • Or if it has a Content-Type header other than:
    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain
  • Or if a ReadableStream or event listeners in XMLHttpRequestUpload are used.

If any of the conditions above are met, a preflight request with the OPTIONS method is sent to the resource URL.

Let’s suppose we are making a POST request to a fictional JSON API at https://api.example.com with a Content-Type of application/json. The preflight request would be like this (some default headers omitted for clarity):

OPTIONS / HTTP/1.1
Host: api.example.com
Origin: http://localhost:8100
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type

If the server is CORS enabled, it will parse the Access-Control-Request-* headers and understand that a POST request is trying to be made from http://localhost:8100 with a custom Content-Type.

The server will then respond to this preflight with which origins, methods, and headers are allowed by using the Access-Control-Allow-* headers:

HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://localhost:8100
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type

If the returned origin and method don’t match the ones from the actual request, or any of the headers used are not allowed, the request will be blocked by the browser and an error will be shown in the console. Otherwise, the request will be made after the preflight.

In our example, since the API expects JSON, all POST requests will have a Content-Type: application/json header and always be preflighted.

Simple requests

Some requests are always considered safe to send and don’t need a preflight if they meet all of the following conditions:

  • The method is:
    • GET
    • HEAD
    • POST
  • Have only these headers:
    • Accept
    • Accept-Language
    • Content-Language
    • Content-Type
    • DPR
    • Downlink
    • Save-Data
    • Viewport-Width
    • Width
  • The Content-Type header is:
    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain
  • No ReadableStream or event listeners in XMLHttpRequestUpload are used.

In our example API, GET requests don’t need to be preflighted because no JSON data is being sent, and so the app doesn’t need to use the Content-Type: application/json header. They will always be simple requests.

Header Value Description
Access-Control-Allow-Origin origin or * Specifies the origin to be allowed, like http://localhost:8100 or * to allow all origins.
Access-Control-Allow-Methods methods Which methods are allowed when accessing the resource: GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH.
Access-Control-Allow-Headers headers Used in response to a preflight request to indicate which headers can be used when making the actual request, aside from the simple headers, which are always allowed.
Access-Control-Allow-Credentials true or false Whether or not the request can be made with credentials.
Access-Control-Expose-Headers headers Specifies the headers that the browser is allowed to access.
Access-Control-Max-Age seconds Indicates how long the results of a preflight request can be cached.

The browser automatically sends the appropriate headers for CORS in every request to the server, including the preflight requests. Please note that the headers below are for reference only, and should not be set in your app code (the browser will ignore them).

All Requests

Header Value Description
Origin origin Indicates the origin of the request.

Preflight Requests

Header Value Description
Access-Control-Request-Method method Used to let the server know what method will be used when the actual request is made.
Access-Control-Request-Headers headers Used to let the server know what non-simple headers will be used when the actual request is made.

A. Enabling CORS in a server you control

The correct and easiest solution is to enable CORS by returning the right response headers from the web server or backend and responding to preflight requests, as it allows to keep using XMLHttpRequest, fetch, or abstractions like HttpClient in Angular.

Ionic apps may be run from different origins, but only one origin can be specified in the Access-Control-Allow-Origin header. Therefore we recommend checking the value of the Origin header from the request and reflecting it in the Access-Control-Allow-Origin header in the response.

Please note that all of the Access-Control-Allow-* headers have to be sent from the server, and don’t belong in your app code.

Here are some of the origins your Ionic app may be served from:

Capacitor

Platform Origin
iOS capacitor://localhost
Android http://localhost

Replace localhost with your own hostname if you have changed the default in the Capacitor config.

Ionic WebView 3.x plugin on Cordova

Platform Origin
iOS ionic://localhost
Android http://localhost

Replace localhost with your own hostname if you have changed the default in the plugin config.

Ionic WebView 2.x plugin on Cordova

Platform Origin
iOS http://localhost:8080
Android http://localhost:8080

Replace port 8080 with your own if you have changed the default in the plugin config.

Local development in the browser

Command Origin
ionic serve http://localhost:8100 or http://YOUR_MACHINE_IP:8100
npm run start or ng serve http://localhost:4200 for Ionic Angular apps.

Port numbers can be higher if you are serving multiple apps at the same time.

Allowing any origin with Access-Control-Allow-Origin: * is guaranteed to work in all scenarios but may have security implications — like some CSRF attacks — depending on how the server controls access to resources and use sessions and cookies.

For more information on how to enable CORS in different web and app servers, please check enable-cors.org

CORS can be easily enabled in Express/Connect apps with the cors middleware:

const express = require('express');
const cors = require('cors');
const app = express();

const allowedOrigins = [
'capacitor://localhost',
'ionic://localhost',
'http://localhost',
'http://localhost:8080',
'http://localhost:8100',
];

// Reflect the origin if it's in the allowed list or not defined (cURL, Postman, etc.)
const corsOptions = {
origin: (origin, callback) => {
if (allowedOrigins.includes(origin) || !origin) {
callback(null, true);
} else {
callback(new Error('Origin not allowed by CORS'));
}
},
};

// Enable preflight requests for all routes
app.options('*', cors(corsOptions));

app.get('/', cors(corsOptions), (req, res, next) => {
res.json({ message: 'This route is CORS-enabled for an allowed origin.' });
});

app.listen(3000, () => {
console.log('CORS-enabled web server listening on port 3000');
});

B. Working around CORS in a server you can’t control

Don’t leak your keys!

If you are trying to connect to a 3rd-party API, first check in its documentation that is safe to use it directly from the app (client-side) and that it won’t leak any secret/private keys or credentials, as it’s easy to see them in clear text in Javascript code. Many APIs don’t support CORS on purpose, in order to force developers to use them in the server and protect important information or keys.

1. Native-only apps (iOS/Android)

Use the HTTP plugin from Ionic Native to make the requests natively from outside the webview. Please note that this plugin doesn’t work in the browser, so the development and testing of the app must always be done in a device or simulator going forward.

Usage in Ionic Angular 4
import { Component } from '@angular/core';
import { HTTP } from '@awesome-cordova-plugins/http/ngx';

@Component({
selector: 'app-home',
templateUrl: './home.page.html',
styleUrls: ['./home.page.scss'],
})
export class HomePage {
constructor(private http: HTTP) {}

async getData() {
try {
const url = 'https://api.example.com';
const params = {};
const headers = {};

const response = await this.http.get(url, params, headers);

console.log(response.status);
console.log(JSON.parse(response.data)); // JSON data returned by server
console.log(response.headers);
} catch (error) {
console.error(error.status);
console.error(error.error); // Error message as string
console.error(error.headers);
}
}
}

2. Native + PWAs

Send the requests through an HTTP/HTTPS proxy that bypasses them to the external resources and adds the necessary CORS headers to the responses. This proxy must be trusted or under your control, as it will be intercepting most traffic made by the app.

Also, keep in mind that the browser or webview will not receive the original HTTPS certificates but the one being sent from the proxy if it’s provided. URLs may need to be rewritten in your code in order to use the proxy.

Check cors-anywhere for a Node.js CORS proxy that can be deployed in your own server. Using free hosted CORS proxies in production is not recommended.

C. Disabling CORS or browser web security

Please be aware that CORS exists for a reason (security of user data and to prevent attacks against your app). It’s not possible or advisable to try to disable CORS.

Older webviews like UIWebView on iOS don’t enforce CORS but are deprecated and are very likely to disappear soon. Modern webviews like iOS WKWebView or Android WebView (both used by Capacitor) do enforce CORS and provide huge security and performance improvements.

If you are developing a PWA or testing in the browser, using the --disable-web-security flag in Google Chrome or an extension to disable CORS is a really bad idea. You will be exposed to all kind of attacks, you can’t ask your users to take the risk, and your app won’t work once in production.

Sources
  • CORS Errors in Ionic Apps
  • MDN

Browsers:

  • Firefox (3.5+)
  • Internet Explorer (9+)
  • Chrome (37+)

Overview

Chrome, Firefox and newer versions of Internet Explorer enforce the Cross-Origin
Resource Sharing standard, and thus only render web fonts served with the
appropriate “Access-Control-Allow-Origin” response header. As Google Fonts may
be viewed on any domain, the fonts are served with the following response
header:

Access-Control-Allow-Origin:*

Potential Cause

Some proxies may strip the header from the response, after which the browser
will not render the fonts.

Diagnosing

With Chrome, check for the relevant warning message in the
DevTools console.

With Firefox, one can either use the Firebug or Live HTTP Headers extensions to
view the response headers to confirm the presence of the CORS response header.

Links

  • https://developer.mozilla.org/En/HTTP_access_control
  • https://www.w3.org/TR/cors/

Web Fonts are not showing up on Firefox when NoScript plugin is installed

Browsers:
* Firefox (3.5+)

Overview

Firefox does not display web fonts when the NoScript plugin is installed.

Potential Cause

By default the NoScript plugin disables @font-face rules.

Solution

Open the NoScript Options, go to the Embeddings tab and uncheck: Forbid
@font-face

Web Fonts are not showing up

Browsers:
* All

Overview

The web fonts used are not showing up.

Potential Cause

There is an error in the API URL, or a style that is not supported by the font
has been requested.

Solution

Make sure that the URL is properly formatted, that the case is respected in the
name of the font (e.g. Droid Serif not droid serif), that the syntax for weight
and styles is respected as well as the syntax to load multiple families (see the
documentation: Getting Started — Syntax.
When fonts are not showing up, looking at the content of the stylesheet can give
more information as to what is going wrong. Copy and paste the URL in your
browser and make sure that you see no error message. For example requesting a
weight not supported by
Droid Serif will show
the following error message:

/* Droid Serif (style: normal, weight: 300) is not available */
/* However, style: normal, weight: normal is available */
/* However, style: italic, weight: normal is available */
/* However, style: normal, weight: bold is available */
/* However, style: italic, weight: bold is available */
/* Not supported. */

Web Fonts are looking thicker when used in a heading

Browsers:
* All

Overview

The fonts look thicker when used in a heading (h1, h2, etc) even though the font
is a normal (400) weight.

Potential Cause

The browser auto-bolded the text.

Solution

Make sure that the correct font-weight is specified in your CSS rule when
applying a font to a header:

h1 {
 font-family: Lobster, cursive;
 font-weight: 400;
}

Issue symptoms

In the browser’s console window, I see one of the below messages:

  • Failed to load … No ‘Access-Control-Allow-Origin’ header
  • Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource … Reason: CORS header ‘Access-Control-Allow-Origin’ missing
  • Failed to load … Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header present on the requested resource. Origin … is therefore not allowed access

One of the keywords usually mentioned in messages is Access-Control-Allow-Origin.

Conditions

A browser-based web application possibly an Apps framework app is attempting to make a cross-origin call to get a shared resource from an external web service. This is known as a CORS request (Cross-Origin-Resource-Sharing).

There is a browser-based CORS standard that manages such cross-origin calls. When certain conditions are not met, errors such as the above happen.

Resolution

This isn’t necessarily a bug because it may relate to a use case that is intentionally not allowed by the user’s web application and remote external service.

When one origin (www.origin1.com) calls another origin (www.origin2.com), that is called a cross-origin request. Certain conditions have to be in place for this request to work. The external service being called (www.origin2.com) needs to return the HTTP header Access-Control-Allow-Origin in its response.

If the external service does not return this header, then the browser’s adherence to the CORS specification stops the request and one of the above errors is returned.

Ask these questions

  • What is the starting point URL of the call (or the origin)? This sometimes is in the error message itself.
  • What is the external service’s URL being called? This is sometimes in the console’s error message.
  • What is being retrieved and why? Is it a PNG file? A script, CSS, or font file? What exactly is being retrieved and what is it being used for? This can give some insights into the use case and why this remote location’s asset is important.
  • Does this external resource require authentication to get? If a redirect is required, the Access-Control-Allow-Origin response header may not be returned and the call will fail. Copy the resource’s URL directly into a new incognito browser tab. This can be a good test of whether it can be accessed under general circumstances but is not a guarantee that it will work in the web app’s code.
  • Can you see OPTIONS HTTP method call in the browser’s Network tab? When custom request headers, authentication, or other conditions exist in the cross-origin request, the browser makes an additional HTTP call. This is also called a preflight call. The web app’s code doesn’t explicitly make it. The browser in the background creates and makes it as it’s part of the CORS specification standard.

When this OPTIONS call is made, certain values need to be in this call’s response for it to succeed and for the actual HTTP call for the resource to happen. If the OPTIONS call fails, then the resource is not retrieved and a CORS error should appear in the browser’s console.

Note down if you see an OPTIONS call. Also, note down if you see a redirect (status 302) call happening right before the OPTIONS call.

If a redirect is happening on an OPTIONS call, then the OPTIONS call will most likely fail. This means the call to get the resource will also fail and trigger a CORS error.

  • What is the use case for making getting external resource? Find out why this external resource is being retrieved in the first place. This may be important in coming up with workarounds or needed changes.
  • Generate a HAR file. Getting a snapshot of the failed call and what happened immediately before and after may help debug the issue and avoid the user from having to reproduce it. Headers in requests and responses can be examined, along with identifying OPTIONS calls and redirects.

Possible next steps

  • Who owns the external server? Perhaps the server can be modified to adhere to the CORS specification standard to return the Access-Control-Allow-Originheader. However, even if the server is something controlled in-house, this isn’t necessarily a cure-all. There may be good reasons that a particular external service does not want to share a resource.

If the external server isn’t something controlled in-house, then maybe work with that vendor or come up with another workaround, assuming the use-case is considered valid.

  • Is the app written using Zendesk Apps framework? A back-end proxy server is available via the client.request() call. Use this proxy by setting cors:false in the client.request’s settings. Note that «false» is also the setting’s default value. Because the proxy service is a back-end service, it doesn’t need to adhere to the browser-based CORS specification, so the cross-origin call may possibly succeed using the proxy.

This also isn’t always a cure-all. The proxy service does not support retrieving binary files or binary information from external services. There may be other app-specific reasons this is not a solution, too.

  • Can the resource be embedded directly into the web app? Instead of going cross-origin to get a resource, consider including it with the web app. This avoids the cross-origin call completely (as it’s now a local resource) and whatever CORS issues may go away. This isn’t always a fix, however. Sometimes external resource URLs are not known ahead of time, or the resource is too large to fit as a local resource, or the resource changes too often to download it as a local static resource.
  • What is the browser version? Despite the CORS specification being a standard, the error messages returned by browsers can be different. Chrome returns different console messages than Firefox. 
  • Sometimes there is no fix. Sometimes a resource request from an external service is not meant to be shared in the context of a browser web app. The resource owner decides if it shares the resource or not. It’s not up to the web app. This might be as designed.

For more information, see these resources:

  • Article from Wikipedia: Cross-origin resource sharing
  • Article from Web.Dev: Cross-Origin Resource Sharing (CORS)
  • Article from Mozilla: Cross-Origin Resource Sharing (CORS)
  • Article from Mozilla: OPTIONS
  • Article from Fetch: Fetch
  • Article from Fetch: CORS protocol

Last updated: 2022-06-16

I’m getting the CORS error «No ‘Access-Control-Allow-Origin'» on my requested resource in Amazon CloudFront. Why am I getting this and how can I resolve it?

Resolution

Note: If you receive errors when running AWS Command Line Interface (AWS CLI) commands, make sure that you’re using the most recent AWS CLI version.

Run the following command to confirm the origin server returns the Access-Control-Allow-Origin header. Replace example.com with the required origin header. Replace https://www.example.net/video/call/System.generateId.dwr with the URL of the resource that’s returning the header error.

curl -H "Origin: example.com" -v "https://www.example.net/video/call/System.generateId.dwr"

If the CORS policy allows the origin server to return the Access-Control-Allow-Origin header, you see a response similar to the following:

HTTP/1.1 200 OK
Server: nginx/1.10.2
Date: Mon, 01 May 2018 03:06:41 GMT
Content-Type: text/html
Content-Length: 3770
Last-Modified: Thu, 16 Mar 2017 01:50:52 GMT
Connection: keep-alive
ETag: "58c9ef7c-eba"
Access-Control-Allow-Origin:
    example.com
Accept-Ranges: bytes

After you set up a CORS policy on your origin server, configure your CloudFront distribution to forward the origin headers to the origin server. If your origin server is an Amazon S3 bucket, then configure your distribution to forward the following headers to Amazon S3:

  • Access-Control-Request-Headers
  • Access-Control-Request-Method
  • Origin

To forward the headers to the origin server, CloudFront has two pre-defined policies depending on your origin type: CORS-S3Origin and CORS-CustomOrigin.

To add a pre-defined policy to your distribution:

  1. Open your distribution from the CloudFront console.
  2. Choose the Behaviors tab.
  3. Choose Create Behavior. Or, select an existing behavior, and then choose Edit.
  4. Under Cache key and origin requests, choose Cache policy and origin request policy. Then, for Origin request policy, choose CORS-S3Origin or CORS-CustomOrigin from the dropdown list. For more information, see Using the managed origin request policies.
    Note: To create your own cache policy instead, see Creating cache policies.
  5. Choose Create Behavior. Or, choose Save changes if you’re editing an existing behavior.

To forward the headers using a cache policy:

  1. Create a cache policy.
  2. Under Cache key settings, for Headers, select Include the following headers. From the Add header dropdown list, choose one of the headers required by your origin.
  3. Fill in the cache policy settings as required by the behavior that you’re attaching the policy to.
  4. Attach the cache policy to the behavior of your CloudFront distribution.

To forward the headers using legacy cache settings:

  1. Open your distribution from the CloudFront console.
  2. Choose the Behaviors tab.
  3. Choose Create Behavior. Or, select an existing behavior, and then choose Edit.
  4. Under Cache key and origin requests, select Legacy cache settings.
  5. In the Headers dropdown list, choose the headers required by your origin. Choose Add custom to add headers required by your origin that don’t appear in dropdown list.
  6. Choose Create Behavior. Or, choose Save changes if you’re editing an existing behavior.

Note: Be sure also to forward the header as part of your client request to CloudFront, which CloudFront forwards to the origin.

Configure the CloudFront distribution’s cache behavior to allow the OPTIONS method for HTTP requests

If you still see errors after updating your CORS policy and forwarding the appropriate headers, allow the OPTIONS HTTP method in your distribution’s cache behavior. By default, CloudFront only allows the GET and HEAD methods. However, some web browsers can issue requests for the OPTIONS method. To turn on the OPTIONS method on your CloudFront distribution:

  1. Open your distribution from the CloudFront console.
  2. Choose the Behaviors tab.
  3. Choose Create Behavior. Or, select an existing behavior, and then choose Edit.
  4. For Allowed HTTP Methods, select GET, HEAD, OPTIONS.
  5. Choose Create Behavior. Or, choose Save changes if you’re editing an existing behavior.

If the origin server isn’t accessible or can’t be set up to return the appropriate CORS headers, configure a CloudFront to return the required CORS headers. To configure, create response headers policies:

  1. Open your distribution from the CloudFront console.
  2. Choose the Behaviors tab.
  3. Choose Create Behavior. Or, select an existing behavior, and then choose Edit.
  4. For Response headers policy:
    Select an existing response policy from the dropdown list.
    -or-
    Choose Create policy to create a new response headers policy . In the new policy, under Cross-origin resource sharing, turn on CORS.
  5. Fill in other settings as needed and choose Create policy.
  6. From the Create Behavior page, choose the policy you created from the dropdown list.
  7. Choose Create Behavior. Or, choose Save changes if you’re editing an existing behavior.

Note: CloudFront typically deploys changes to distributions within five minutes. After you edit your distribution, invalidate the cache to clear previously cached responses.


Did this article help?


Do you need billing or technical support?

AWS support for Internet Explorer ends on 07/31/2022. Supported browsers are Chrome, Firefox, Edge, and Safari.
Learn more »

Понравилась статья? Поделить с друзьями:
  • Cropmark error not found
  • Crontab error log
  • Crontab error bad minute
  • Crontab error bad hour
  • Crontab error bad day of week