如何使用NGINX入口控制器从Cloudflare恢复原始客户端IP

时间:2019-06-07 06:40:07

标签: docker nginx kubernetes google-kubernetes-engine cloudflare

我正在使用Cloudflare作为CDN,并且为客户端隐藏了真实IP地址 我正在使用NGINX入口控制器作为Google Kubernetes引擎中运行的负载平衡器 因此,我试图恢复原始IP地址并尝试遵循此链接https://support.cloudflare.com/hc/en-us/articles/200170706-How-do-I-restore-original-visitor-IP-with-Nginx- 因为我需要对同一个键“ set-real-ip-from”使用多个值,所以如何在configmap中为Nginx入口实现此功能?

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingressname
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/proxy-body-size: "0"
    nginx.ingress.kubernetes.io/affinity: "cookie"
    nginx.ingress.kubernetes.io/session-cookie-name: "route"
    nginx.ingress.kubernetes.io/session-cookie-expires: "172800"
    nginx.ingress.kubernetes.io/session-cookie-max-age: "172800"
spec:
  tls:
  - hosts:
    - example.com
    secretName: sslcertificate
  rules:
  - host: example.com
    http:
      paths:
      - backend:
          serviceName: service
          servicePort: 80
        path: /

2 个答案:

答案 0 :(得分:1)

我也有这个问题,花了我很多时间才能解决,但显然我所需要的只是这种配置:

apiVersion: v1
data:
  # Cloudflare IP ranges which you can find online
  proxy-real-ip-cidr: "173.245.48.0/20,103.21.244.0/22,103.22.200.0/22,103.31.4.0/22,141.101.64.0/18,108.162.192.0/18,190.93.240.0/20,188.114.96.0/20,197.234.240.0/22,198.41.128.0/17,162.158.0.0/15,104.16.0.0/12,172.64.0.0/13,131.0.72.0/22,2400:cb00::/32,2606:4700::/32,2803:f800::/32,2405:b500::/32,2405:8100::/32,2a06:98c0::/29,2c0f:f248::/32"
  # This is the important part
  use-forwarded-headers: "true"
  # Still works without this line because it defaults to X-Forwarded-For, but I use it anyways
  forwarded-for-header: "CF-Connecting-IP"
kind: ConfigMap
metadata:
  name: nginx-configuration
  namespace: ingress-nginx
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx

IMO这一点在文档中还不清楚。我必须搜索大量的问题和实际的模板文件本身才能找到答案。

答案 1 :(得分:0)

为了从X-Forwarded-For头中检索数据并为客户端获取真实的IP地址,您必须启用代理协议(尤其是Nginx Ingress控制器ConfigMap),然后为访问者添加IP /网络。

apiVersion: v1
data:
  proxy-real-ip-cidr: 103.21.244.0/22,103.22.200.0/22,103.31.4.0/22
  use-proxy-protocol: "true"
kind: ConfigMap
metadata:
  labels:
    app: nginx-ingress
  name: nginx-ingress-controller
  namespace: default

希望这对您有帮助!