Niccolo
Niccolo

Reputation: 815

CORS Access-Control-Allow-Origin Error on Drupal 7 with Cloudflare

We have been having the problem where we get errors of the format.

Font from origin 'https://example.com' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://www.example.com' is therefore not allowed access.

We also get a "Redirect at origin" error.

We are using Drupal 7 and Cloudflare.

we have attempted to edit .htaccess to include

Header set Access-Control-Allow-Origin "https://example.com"
Header set Access-Control-Allow-Origin "https://www.example.com"

Tried quite a lot;

So far no joy.

As this approach is not working, I am wondering if something is being missed or if there is an alternate approach, such as why we are getting origin 'https://example.com' being in the request via Drupal and not 'https://www.example.com'.

Last note it that when I review some resources I see two distinct patterns. If a resource has status of "301 Moved Permanently" in the request headers there is

Where the status is "304 Not Modified"

It's odd that there is any www at all; htaccess should be redirecting and it is absent from base_url.

Upvotes: 4

Views: 5046

Answers (1)

c-tools
c-tools

Reputation: 133

I have experienced a very similar issue.

Be ensured that module headers is enabled

1 - To enable mod headers on Apache2 (httpd) you need to run this command:

sudo a2enmod headers

Then restart Apache

sudo service apache2 restart

2 - To allow Access-Control-Allow-Origin (CORS) authorization for specific origin domains for all files, add this in your .htaccess

<IfModule mod_headers.c>
 Header set Access-Control-Allow-Origin https://example.org
 Header set Access-Control-Allow-Origin https://example.com
 Header set Access-Control-Allow-Origin https://example.eu
   ## SECURITY WARNING : never add following line when site is in production
   ## Header set Access-Control-Allow-Origin "*"
</IfModule>

2 - To allow Access-Control-Allow-Origin (CORS) authorization for specific origin domains and for fonts only in our example, use FilesMatch like in the following section in your .htaccess

<FilesMatch "\.(ttf|otf|eot|woff|woff2)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin https://example.org
    Header set Access-Control-Allow-Origin https://example.com
    Header set Access-Control-Allow-Origin https://example.eu
  </IfModule>
</FilesMatch>

After making changes in .htaccess file, no need to restart your apache webserver

Upvotes: 1

Related Questions