Ingress 兼容前端https & http 跨域配置access-control-allow-origin
场景说明:
前端域名a.com 访问后端b.com 域名,其中b.com 使用Ingress 配置,需要支持http://a.com 和https://a.com 两种前端域名跨域方式访问b.com 。
一、使用Ingress 原生跨域Annotations 配置只可满足其中一种情况
注意,官方最新的文档cors-allow-origin 支持配置多个域名,但在我们使用的比较旧的版本0.32 中配置两个直接被设置为* ,导致失败
annotations:
nginx.ingress.kubernetes.io/enable-cors: 'true'
nginx.ingress.kubernetes.io/cors-allow-origin: 'https://a.com'
nginx.ingress.kubernetes.io/cors-allow-methods: '*'
nginx.ingress.kubernetes.io/cors-allow-headers: '*'
nginx.ingress.kubernetes.io/cors-allow-credentials: 'true'
二、以上配置生成的nginx.conf 片段
if ($request_method = 'OPTIONS') {
more_set_headers 'Access-Control-Allow-Origin: *';
more_set_headers 'Access-Control-Allow-Credentials: true';
more_set_headers 'Access-Control-Allow-Methods: *';
more_set_headers 'Access-Control-Allow-Headers: *';
more_set_headers 'Access-Control-Max-Age: 1728000';
more_set_headers 'Content-Type: text/plain charset=UTF-8';
more_set_headers 'Content-Length: 0';
return 204;
}
more_set_headers 'Access-Control-Allow-Origin: *';
more_set_headers 'Access-Control-Allow-Credentials: true';
more_set_headers 'Access-Control-Allow-Methods: *';
more_set_headers 'Access-Control-Allow-Headers: *';
三、根据自动生成的nginx.conf 改为使用configuration-snippet 配置
annotations:
nginx.ingress.kubernetes.io/configuration-snippet: |
if ($request_method = 'OPTIONS') {
more_set_headers "Access-Control-Allow-Origin: $http_origin";
more_set_headers 'Access-Control-Allow-Credentials: true';
more_set_headers 'Access-Control-Allow-Methods: *';
more_set_headers 'Access-Control-Allow-Headers: *';
more_set_headers 'Access-Control-Max-Age: 1728000';
more_set_headers 'Content-Type: text/plain charset=UTF-8';
more_set_headers 'Content-Length: 0';
return 204;
}
more_set_headers "Access-Control-Allow-Origin: $http_origin";
more_set_headers 'Access-Control-Allow-Credentials: true';
more_set_headers 'Access-Control-Allow-Methods: *';
more_set_headers 'Access-Control-Allow-Headers: *';
nginx.ingress.kubernetes.io/ssl-redirect: 'false'
|