Kubernetes Ingress之 ingress-nginx CORS設置

在前後端分離的情況下 (web和api) 就會牽扯到跨域問題(Cross-origin resource sharing,縮寫: CORS ),用於讓網頁的受限資源能夠被其他域名的頁面訪問的一種機制。

當 web頁面要請求外部域名時會被阻擋,因為CORS機制問題,這時候就需要在後端API 設置些跨域配置。

web 域名 -> http://k8s.com

api 域名 -> http://api.k8s.com/api

若還有問題 可以直接查看ingress-nginx log

# 查看 ingress log  
kubectl logs pod/ingress-nginx-controller-xxx -f -n ingress-nginx

以下是 一個允許特定域名跨域的ingress-nginx 配置的版本使用php-fpm 。

ingress-nginx 官網

# ingress-nginx  
# ingress-api.yaml 
# 主要設置為 enable-cors, cors-allow-methods , cors-allow-credentials, cors-allow-origin 
 
apiVersion: v1 
kind: ConfigMap 
metadata: 
  name: php-fpm-ingress-nginx 
data: 
  DOCUMENT_ROOT: "{prj_dir}/http" 
  SCRIPT_FILENAME: "{prj_dir}/$fastcgi_script_name" 
  QUERY_STRING: "$query_string" 
  REQUEST_METHOD: "$request_method" 
  CONTENT_TYPE: "$content_type" 
  CONTENT_LENGTH: "$content_length" 
  SCRIPT_NAME: "$fastcgi_script_name" 
  REQUEST_URI: "$request_uri" 
  DOCUMENT_URI: "$document_uri" 
  SERVER_PROTOCOL: "$server_protocol" 
  REQUEST_SCHEME: "$scheme" 
  HTTPS: "$https" 
  GATEWAY_INTERFACE: "CGI/1.1" 
  SERVER_SOFTWARE: "nginx/$nginx_version" 
  REMOTE_ADDR: "$remote_addr" 
  REMOTE_PORT: "$remote_port" 
  SERVER_ADDR: "$server_addr" 
  SERVER_PORT: "$server_port" 
  SERVER_NAME: "$server_name" 
  REDIRECT_STATUS: "200" 
 
--- 
 
apiVersion: networking.k8s.io/v1 
kind: Ingress 
 
metadata: 
  name: php 
  annotations: 
    nginx.ingress.kubernetes.io/backend-protocol: "FCGI" 
    nginx.ingress.kubernetes.io/fastcgi-index: "index.php" 
    nginx.ingress.kubernetes.io/fastcgi-param-X-Real-IP: "$http_x_forwarded_for" 
    nginx.ingress.kubernetes.io/fastcgi-params-configmap: "php-fpm-ingress-nginx" 
    nginx.ingress.kubernetes.io/rewrite-target: "/api.php" 
    # 跨域設定 
# --------------- 
    nginx.ingress.kubernetes.io/enable-cors: "true" 
    nginx.ingress.kubernetes.io/cors-allow-methods: "PUT, GET, POST, DELETE, PATCH, OPTIONS" # separated by ','  
    nginx.ingress.kubernetes.io/cors-allow-credentials: "true" #控制CORS期間是否能傳遞憑證 
    nginx.ingress.kubernetes.io/cors-allow-origin: "http://k8s.com,https://k8s.com" # 是否要限制特定域名 
    # 若需要特定header 可以透過以下配置參數, 注意: 若是* 並不代表所有header帶過去web 頁面 
    # 若後端有自定義header時 例如language , 則需要允許 不然web頁面 api會無法請求 
    # nginx.ingress.kubernetes.io/cors-allow-headers: language,Authorization, Date, ETag, Expires, Link, Location, Set-Cookie, Vary, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-Total-Count 
    nginx.ingress.kubernetes.io/cors-allow-headers: "language" 
# --------------- 
 
spec: 
  ingressClassName: nginx 
  rules: 
    - host: api.k8s.com 
      http: 
        paths: 
        - path: /api(/|$)(.*) 
          pathType: ImplementationSpecific 
        #- path: /api 
        #  pathType: Prefix 
          backend: 
            service: 
              name: php 
              port: 
                number: 9000