从nginx ingress控制器v5.4.0起,cors行为可通过policy资源统一定义并复用于virtualserver和ingress;其工作原理是创建含spec.cors的policy,再通过spec.policies或nginx.org/policies注释关联到流量资源。

从 NGINX Ingress 控制器 (NIC) v5.4.0 开始,您可以在 A 中定义一次 CORS 行为Policy资源化,并在两者之间持续应用VirtualServer而且Ingress交通路径。
在整个博客中,我们重点关注:
- NGINX Ingress 控制器中 CORS 策略的工作原理。
- 在哪里安装VirtualServer而且Ingress。
为什么要使用 CORS 政策?
许多团队从每份资源调整开始,并迅速出现偏离。使用专用Policy因为 CORS 会给你:
- 允许起源、方法和头部的单一真相来源。
- 跨服务和命名空间重复使用。
- 更清洁的评价,因为CORS行为与路线逻辑是隔离的。
NGINX Ingress 控制器中 CORS 策略的工作原理
在高层次上:
- 创建一个Policy资源支持spec.cors
- 在定义流量时将其连接:
- VirtualServer.spec.policies(或路线/分销政策)
- Ingress通过nginx.org/policies注释
- 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
http:
paths:
- path: /tea
pathType: Prefix
backend:
service:
name: tea-svc
port:
number: 80
|
需要记住的重要行为:
- CORS 政策可同时适用于两者VirtualServer而且Ingress。
- 为VirtualServer路由/分流策略在规范级别上覆盖同类型策略。
- 用于认证的 CORS(allowCredentials: true需要明确来源。
预防大多数问题的生产检查
上线前,请明确验证以下内容:
- 非允许来源不接收Access-Control-Allow-Origin。
- allowCredentials: true仅使用显性来源(而非*)










