Ingress nginx enable Cors headers only on Specific Hosts

5/21/2021

I have an Ingress configuration, I want to enable cors headers on some specific hosts!

I set the annotation in the ingress to

nginx.ingress.kubernetes.io/configuration-snippet: |
        more_set_headers "Access-Control-Allow-Origin: $http_origin";
nginx.ingress.kubernetes.io/enable-cors: "true"
nginx.ingress.kubernetes.io/cors-allow-credentials: "true"

This works but, also will set Access-Control-Allow-Origin in some other hosts For example:

curl 'https://example.com' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:88.0) Gecko/20100101 Firefox/88.0' -H 'Accept: application/json' -H 'Accept-Language: en,en-US;q=0.7,en;q=0.3' --compressed -H 'Origin: https://hacker.org' -H 'Connection: keep-alive' -v

The result would be Access-Control-Allow-Origin: hacker.org which is not what I expect!

I want to configure the ingress in a way that it sets the Access-Control-Allow-Origin only on some specific hosts!

I tried this annotation!

    nginx.ingress.kubernetes.io/configuration-snippet: |
         if ($http_origin ~*  'https://example.com') {
              more_set_headers "Access-Control-Allow-Origin: $http_origin";
         }
    nginx.ingress.kubernetes.io/enable-cors: "true"
    nginx.ingress.kubernetes.io/cors-allow-credentials: "true"

But does not work!

I want the ingress configured to set Cors headers only on some specific hosts!

-- Mohamed chiheb Ben jemaa
kubernetes
kubernetes-ingress
nginx
nginx-ingress

1 Answer

5/21/2021

This is due to the fact that you enabled cors nginx.ingress.kubernetes.io/enable-cors: "true" and with that the default for nginx.ingress.kubernetes.io/cors-allow-origin came into play which is *. Simply configure it with the appropriate annotation like so:

nginx.ingress.kubernetes.io/enable-cors: "true"
nginx.ingress.kubernetes.io/cors-allow-origin: "https://origin-site.com"

More information can be found here: https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/#enable-cors

-- F1ko
Source: StackOverflow