You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在GCP GKE的Google Ingress中配置多路径指向同一后端服务?

Google Ingress 路径规则优化方案(GKE环境)

Google Ingress本身不支持Nginx那样的正则路径匹配,没法用单条规则覆盖/api、/auth、/admin这类独立前缀,但可以通过以下两种方式优化配置,同时更好地实现“阻止不安全请求”的目标:

1. 配置默认后端拦截未匹配请求

如果你的需求是仅允许指定路径的请求到达服务,其余请求直接拒绝,可以给Ingress添加一个专门的默认后端,处理所有未匹配到规则的请求(返回403/404)。这种方式不需要修改现有三个路径规则,但能明确实现拦截逻辑,比单纯重复规则更清晰。

步骤1:创建拒绝服务

先部署一个简单的服务,用于返回403响应:

# 拒绝服务的Service
apiVersion: v1
kind: Service
metadata:
  name: deny-service
spec:
  selector:
    app: deny-app
  ports:
  - port: 80
    targetPort: 80
---
# 拒绝服务的Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
  name: deny-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: deny-app
  template:
    metadata:
      labels:
        app: deny-app
    spec:
      containers:
      - name: nginx
        image: nginx:alpine
        ports:
        - containerPort: 80
        volumeMounts:
        - name: config
          mountPath: /etc/nginx/conf.d
      volumes:
      - name: config
        configMap:
          name: deny-config
---
# Nginx配置文件,返回403
apiVersion: v1
kind: ConfigMap
metadata:
  name: deny-config
data:
  default.conf: |
    server {
        listen 80;
        server_name _;
        return 403;
    }

步骤2:修改Ingress配置

在原Ingress中添加defaultBackend字段,将未匹配请求导向拒绝服务:

spec:
  # 默认后端:处理所有未匹配的请求
  defaultBackend:
    service:
      name: deny-service
      port:
        number: 80
  rules:
  - http:
      paths:
      - backend:
          service:
            name: my-api-service
            port:
              number: 80
        path: /api
        pathType: Prefix
      - backend:
          service:
            name: my-api-service
            port:
              number: 80
        path: /auth
        pathType: Prefix
      - backend:
          service:
            name: my-api-service
            port:
              number: 80
        path: /admin
        pathType: Prefix

这样所有不在三个前缀范围内的请求都会被返回403,直接阻止非授权路径的访问。

2. 结合Cloud Armor强化安全防护(更推荐)

如果你的核心目标是阻止不安全请求(比如SQL注入、XSS、恶意扫描等),仅靠路径规则是远远不够的。可以结合Google Cloud Armor的WAF能力,和Ingress绑定后实现更全面的安全拦截:

  1. 在Google Cloud控制台创建Cloud Armor安全策略,添加规则拦截常见攻击(比如预定义的OWASP核心规则集)。
  2. 在Ingress的metadata.annotations中添加绑定配置:
metadata:
  annotations:
    networking.gke.io/v1beta1.FirewallPolicy: "你的安全策略名称"

这种方式既能通过路径规则做基础路由,又能借助Cloud Armor的专业防护能力阻止真正的不安全请求,比单纯依赖路径规则更可靠。


内容的提问来源于stack exchange,提问作者nsbm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 05:36:00