Loading...


Related Products


Date Published: February 11, 2022

Enabling CORS in Drupal 8/9 on Acquia Cloud Site Factory

 

Cross-origin resource sharing (CORS) is disabled by default in Drupal 8. In a self-hosted, Acquia Cloud Enterprise, or Acquia Cloud Professional, you would edit the settings.php and services.yml files within the site directory. In Acquia Cloud Site Factory you must use a factory hook to customize the settings.php file. In this guide, we will show you how to enable CORS for Acquia Cloud Site Factory sites using Factory Hooks.

NOTE: There is a known bug in Drupal 8 core around CORS and Varnish caching

Please see our Knowledgebase Article.

Steps 

1: Check out a local copy of your site code

If you need help with this step, please check out  Git best practices on Acquia Cloud Site Factory.

2: Create a services.yml file

In the /factory-hooks/post-settings-php/ directory, create a new services.yml file. Copy the CORS-specific entries from the default.services.yml file into the new services.yml file and modify to suit your needs. If you need help starting out, review examples found in the comments section of this page on drupal.org: Opt-in CORS support

3: Create the hook file

Files executed by the factory hooks must have a .php extension. Create a services.php file in the same directory. Add these lines to the file: 

<?php

$settings['container_yamls'][] = __DIR__ . '/services.yml';

Commit both files to your repository. After making these changes to your codebase, it is time to test in non-production. 

More information about Acquia Cloud Site Factory Hooks can be found in our product guide: Hooks in Acquia Cloud Site Factory

4: Clear caches

Since this involves a change to the Drupal container (which is cached), this requires a Drupal cache clear (e.g. drush cr --uri=mysite.com)

Testing

You can verify whether CORS-related headers appear by using either your browser's network inspector, or a curl command.

Note that the incoming request needs to have an Origin header in order for Drupal to trigger the right code which will inject the headers.

Here is an example using curl:

# NOTE: This example assumes that https://example.mydrupalsite.com is a valid Origin 
#   as per the Drupal settings.
$ curl -sSLIXGET -H "Origin: https://example.mydrupalsite.com" "http://example.mydrupalsite.com/filter/tips?cachebust="`date +%s` 
HTTP/1.1 200 OK
X-Generator: Drupal 8 (https://www.drupal.org)
X-Drupal-Cache: MISS
{ ... snip ... }
Access-Control-Allow-Origin: https://example.mydrupalsite.com
Access-Control-Expose-Headers: 
{ ... snip ... }

 

Did not find what you were looking for?

If this content did not answer your questions, try searching or contacting our support team for further assistance.

Back to Section navigation
Back to Site navigation