CORS missmatch because of http

I don’t understand why i get this error.

sub.domain.app/:1 XMLHttpRequest cannot load http://domain.app/wc-api/v3. The 'Access-Control-Allow-Origin' header contains the invalid value 'sub.domain.app'. Origin 'http://sub.domain.app' is therefore not allowed access.

The site domain.app is a wordpress install and sub.domain is just static html. And I the error occurs when i try to fetch via ajax (vue-router).

Read More

Both the domains are on homestead. And I have set up nginx to allow the subdomain to do CORS requests.

location / {
    try_files $uri $uri/ /index.php?$query_string;
        add_header 'Access-Control-Allow-Origin' "http://sub.domain.app";
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}

I’m hoping someone smarter than me can help me solv this. Thanks in advance!

Related posts

2 comments

  1. It looks like you want to allow requests for the main domain and a subdomain. CORS specification does not permit that in a single header. Either the exact domain or ‘*’. You have to dynamically check the domain and set that in the header.

    With NGINX:

     server {
    
        root /path/to/your/stuff;
    
        index index.html index.htm;
    
         set $cors "";
    
        if ($http_origin ~* (.*.domain.com)) {
            set $cors "true";
        }
    
        server_name domain.com;
    
        location / {
    
            if ($cors = "true") {
                add_header 'Access-Control-Allow-Origin' "$http_origin";
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT';
                add_header 'Access-Control-Allow-Credentials' 'true';
                add_header 'Access-Control-Allow-Headers' 'User-Agent,Keep-Alive,Content-Type';
            }
    
    
            if ($request_method = OPTIONS) {
                return 204;
            }
    
        }
    }
    

    More here.

    With PHP

    Examine $_SERVER['HTTP_HOST'] and search it for your desired (sub)domains, and then conditionally set your CORS headers with PHP.

    So, something like this:

    $allowed_hosts = array('sub.domain.app', 'domain.app');
    
    if (in_array($allowed_hosts, $_SERVER['HTTP_HOST'])) {
      header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_HOST']);
    }
    
  2. The page where you would like to get your result by ajax at the top of this page add the following :

    <?php header('Access-Control-Allow-Origin: *'); ?>
    

    it will solve your problem.

Comments are closed.