自NGINX Ingress控制器v5.4.0起,CORS策略可通过Policy资源统一配置,并复用于VirtualServer和Ingress资源。具体而言,先创建一个包含spec.cors字段的Policy,再通过spec.policies字段或nginx.org/policies注解将其关联到相应的流量路由资源上。

从NGINX Ingress控制器(NIC)v5.4.0开始,您可以在Policy资源中一次性定义CORS跨域规则,并应用到VirtualServer和Ingress两种流量路径上。
本文将重点介绍以下内容:
- NGINX Ingress控制器中CORS策略的工作原理与核心机制。
- 如何在VirtualServer和Ingress资源上配置并应用CORS策略。
为什么要使用CORS策略?
许多团队最初会在每个资源上单独配置CORS,但很快就会发现配置不一致、维护困难。使用专门的Policy资源来管理CORS,具有以下明显优势:
- 允许的源、方法和头部信息有了单一的真实来源,避免了不同配置间的不一致。
- 可在不同服务和命名空间之间重复使用,减少重复劳动。
- 审核更加清晰,CORS行为与路由逻辑完全隔离,修改时不会影响其他部分。
NGINX Ingress控制器中CORS策略的工作原理
整个配置流程分为以下三步:
- 创建一个Policy资源,并在其中配置
spec.cors字段。 - 在定义流量路由时将其关联:
- 对于VirtualServer,通过
spec.policies字段(也可在路由/分流策略级别覆盖)。 - 对于Ingress,通过
nginx.org/policies注解。
- 对于VirtualServer,通过
- NGINX Ingress控制器会自动生成对应的NGINX CORS配置,为预检请求和实际跨域请求返回正确的响应头部。
CORS策略示例:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
apiVersion: k8s.nginx.org/v1 kind: Policy metadata: name: cors-policy spec: cors: allowOrigin: - https://app.example.com allowMethods: - GET - POST - PUT - OPTIONS allowHeaders: - Content-Type - Authorization - X-Requested-With exposeHeaders: - X-Total-Count - X-Page-Size allowCredentials: true maxAge: 86400 |
引用CORS策略的VirtualServer示例:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
apiVersion: k8s.nginx.org/v1 kind: VirtualServer metadata: name: webapp spec: host: webapp.example.com policies: - name: cors-policy upstreams: - name: webapp service: webapp-svc port: 80 routes: - path: /test action: pass: webapp |
CORS策略在Ingress下的引用示例:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: cafe-ingress annotations: nginx.org/policies: "cors-policy" spec: ingressClassName: nginx rules: - host: cafe.example.com https: paths: - path: /tea pathType: Prefix backend: service: name: tea-svc port: number: 80 |
需要记住的重要行为:
- CORS策略可以同时应用于VirtualServer和Ingress两种资源。
- 在VirtualServer中,路由/分流策略级别的policy会覆盖规范级别的同类型policy。
- 如果启用了
allowCredentials: true,则allowOrigin必须明确指定具体的源,不能使用通配符*。
生产环境检查:预防大多数CORS配置问题
在生产环境上线前,务必验证以下关键点:
- 对于未允许的源,不应返回
Access-Control-Allow-Origin响应头。 - 当
allowCredentials: true时,只使用显式指定的来源,不要使用通配符*。
