HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

CORS and subdomains - do subdomains matter?

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
andmattercorssubdomains

Problem

Will CORS ever be a problem when you have x.example.com going to y.example.com or only if the root domain is different?

Solution

CORS is not allowing subdomains, so you need to specify them in your server configuration.

If you are using NGINX (or you could use it as a proxy and solve your problem) by providing dynamic cors header response

server {

    root /path/to/your/stuff;

    index index.html index.htm;

     set $cors "";

    if ($http_origin ~* (.*\.yoursweetdomain.com)) {
        set $cors "true";
    }

    server_name yoursweetdomain.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;
        }

    }
}


Source here

Code Snippets

server {

    root /path/to/your/stuff;

    index index.html index.htm;

     set $cors "";

    if ($http_origin ~* (.*\.yoursweetdomain.com)) {
        set $cors "true";
    }

    server_name yoursweetdomain.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;
        }

    }
}

Context

StackExchange DevOps Q#8944, answer score: 4

Revisions (0)

No revisions yet.